I have created a window
When I do this
w->Create (...);
w->DestroyWindow ();
w->Create (...);
The program crashes
Can any one help?
We don't know enough about your MFC window class. If it is derived from CFrameWnd or CView, it is going to crash. That is because after those windows are destroyed, their C++ memory pointer (this) is not valid anymore. It points to an area of memory that has been freed by the C++ memory allocator. Attempting to dereference it will cause a crash. Because, in the PostNcDestroy() overrides, the CFrameWnd and CView classes call "delete this".
void CFrameWnd::PostNcDestroy()
{
// default for frame windows is to allocate them on the heap
// the default post-cleanup is to 'delete this'.
// never explicitly call 'delete' on a CFrameWnd, use DestroyWindow instead
delete this;
}
void CView::PostNcDestroy()
{
// default for views is to allocate them on the heap
// the default post-cleanup is to 'delete this'.
// never explicitly call 'delete' on a view
delete this;
}
Related
Suppose we have a class with a smart pointer. This class initializes a subsystem that the smart pointer relies on: similarly, this class closes the subsystem upon destruction.
If the smart pointer relies on said subsystem to free its memory, then if the destructor closes the subsystem first an issue arises.
class FontManager {
public:
FontManager() {
if(TTF_Init() < 0) {
printf( "SDL_ttf could not init! SDL_ttf Error: %s\n", TTF_GetError() );
return;
}
}
~FontManager() {
TTF_Quit();
}
std::unique_ptr<TTF_Font> font;
void operator()(TTF_Font* font) const { TTF_CloseFont(font); }
};
If I were using raw pointers the destructor would look like this.
~FontManager() {
// font is raw pointer
TTF_CloseFont(font);
TTF_Quit();
}
So, what gets called first, the pointer's destructor or the class' destructor?
Just as subobjects are constructed at the beginning of a class’s constructor (in the member initializer list, perhaps implicitly), they are destroyed at the end of the destructor (in the reverse order of their construction, as usual).
You can of course reset your pointers manually in your destructor; they will still be destroyed at the end of it, but with no effect. But the real answer is to encapsulate the subsystem (initialization) as its own resource, add an instance of that new class as an earlier member, and then let the containing class use the implicit destructor. This has the additional benefit of guaranteeing that the subsystem is initialized when you use it to allocate the smart pointer’s object.
I studding C++ concept. I'm confused in constructor and Destractor concept. Destructor will be invoked implicitly by the compiler upon exit from the program. But in my program, only constructor called.
#include <iostream>
using namespace std;
class A
{
int i;
public:
A()
{
cout<<"Constructor call"<<endl;
}
~A()
{
cout<<"Destructtor call"<<endl;
}
};
int main()
{
A *a = new A();
}
Output:
Constructor call
So, I have question : Why destructor not call implicit by the compiler upon exit program?
Why destructor not call implicit by the compiler upon exit program?
Because dynamically allocated objects are not destroyed automatically. That is how the language has been specified. Tracking the destruction of dynamic objects would require runtime / memory overhead.
Solution: Do not leak dynamically allocated objects.
There are 2 "types" of variable lifetime in C++. Dynamic and automatic.
Automatic is something like :
void foo()
{
int i; // automatic storage
} // destroys i
Here, i will be destructed the moment it leaves scope (after foo returns). You can check this for yourself by making your object have an automatic lifetime:
int main()
{
A a; // calls A's constructor and allocates memory.
} //calls A's destructor and frees the memory used.
You'll see that both the constructor and the destructor will get called.
The second form is dynamically allocated memory. You can dynamically allocate memory by using new (like you did) and free that memory by using delete. The compiler won't do this for you.
This means that, to destruct your object you have to call delete explicitly yourself:
int main()
{
A* a = new A();
delete a; // calls A's destructor and frees the memory used.
}
If you do not call delete (like your code) then the moment the program leaves main the pointer a is destroyed and now we have a piece of memory that nothing can reach and thus nobody can clean up (with delete) which means you're leaking memory.
However, modern operating systems reclaim all memory used by the program automatically the moment the program ends so at this point it won't matter too much. This does mean your destructor won't be called as you've just witnessed.
Dynamically allocated memory allows you to do some nifty tricks like controlling the lifetime of your objects to the point where you want to destroy them explicitly yourself with delete. The problem with using new and delete is that it's so easy to forget a single delete and your program will already leak memory, which is why it's advised to stay away from this way of allocation.
If for some reason you absolutely need dynamic lifetime then use a smart pointer like std::unique_ptr that will call new and delete for you the moment it goes out of scope.
You create the object dynamically with new. The destructor will only be called when the objected is deleted with delete.
To prevent memory leaks, you could/should use smart pointers like unique_ptr.
In any case, the memory itself will of course be released when the process ends.
The destructor is never called in your code because the object is never destroyed.
You dynamically allocate the A object and you never deallocate it. Add delete a; into main() and you'll see the destructor in action:
int main()
{
A *a = new A();
delete a;
return 0;
}
In your main function, you create a pointer variable that you must delete it by delete a at end of main function.
Because you have a memory leak. You dynamically created an object with new, promising that you would manage the lifetime of the object and clean it up later with delete. Then you broke that promise.
If you create an object in the usual fashion:
A a;
then it will be destroyed automatically for you.
This question relates to C++ game engine, called AppGameKit (AGK).
I've created a separate class for Text so that I don't have to call AGK functions when creating Text. Here's the simple class:
Text.h
class Text
{
private: int _ID;
void Destory();
public:
void AddText();
Text(int ID);
~Text();
};
Text::Destroy()
{
agk::DeleteText(_ID);
}
Text::~Text()
{
Text::Destroy();
}
Now my question is when I'm calling this class in any other class, say MainMenu, do I have to delete the button in the class MainMenu that I'm creating using this class or will the destructor of Text will automatically get called and delete the button.
MainMenu.cpp
MainMenu::Initilization()
{
Text * mainText = new Text(1);
}
MainMenu::Destory()
{
agk::DeleteText(1); // DO I HAVE TO DO THIS?
}
MainMenu::~MainMenu()
{
MainMenu::Destory();
}
AGK function delete is called to delete text so that the memory is deallocated. Similar to C++ delete keyword.
Personally, I think deleting the button in MainMenu class should be unnecessary but I'm confused as to whether the destructor of Text class is even called. Please let me know if you think I'm wrong.
Every new has to be balanced with a delete else you will leak memory. (You can use classes like std::unique_ptr which will manage the deletion for you but they still call delete under the hood).
Currently, mainText goes out of scope at the end of the Initilization function, so you lose the pointer that you need for a successful delete.
Do I have to manually delete object even after destructor?
No.
You called Text * mainText = new Text(1); in Initialization, so call delete mainText in Destroy
When you call delete mainText
If mainText is not null its destructor would be called
If mainText is not null its memory would be freed
No need to mention, the destructor already calls agk::DeleteText
The basic rule of thumb in C++ is for every new() there must be a delete(). This ensures that there would be no memory leakage.
In most modern OS, there is no memory leakage ever. Once your program exits, the OS claims back the memory and puts it back in heap.
But what happens when your program is running for a long time. This means you will keep leaking memory until your program exits.
So it's best to delete the allocated memory and adhere to the rule of thumb.
Hope it helps!!
Does this cause a memory leak because pWinsock didn't get deleted inside the fonction?
Winsock* CreateWinsock()
{
Winsock* pWinsock=new Winsock;
return pWinsock;
}
Edit: Actually, I cannot delete my pointer since it is a member of Game (pWinsock) that received the newly created Winsock in the code above. Is there anything wrong with this?
class Game{
public:
Game();
~Game();
void CreateWindowClass(HINSTANCE);
void CreateRessources(HINSTANCE);
void ShowLoginScreen();
HWND Getm_hWnd();
public:
D2DResources* pD2DResources;
Winsock* pWinsock;
MessageLog* pMessageLog;
private:
HWND m_hWnd;
};
Watch out, if you delete the memory in the function the returned pointer will become a dangling pointer, as the memory for it has already been cleared. Dereferencing such a pointer is undefined behavior.
The program only causes a memory leak if the caller does not remember to delete the memory for themselves. Since you allocated memory within the function and returned it, it must be deleted somehow after the call. To delete the memory, it would look something like this:
Winsock *ptr = CreateWinsock(); // memory passed to ptr
// ...
delete ptr; // delete memory
The problem is that depending on the caller to delete the memory is quite cumbersome and unreliable. These kinds of potential problems can be alleviated through the use of smart pointers such as unique_ptr or shared_ptr. These objects delete the memory when their destructors are called, allowing great flexibility. Here's an example of how it would look for your program:
std::unique_ptr<Winsock> CreateWinsock()
{
return std::unique_ptr<Winsock>(new Winsock);
}
std::unique_ptr<Winsock> ptr = CreateWinsock();
There's no need to explicitly delete the pointer as the encapsulating smart pointer now has that responsibility.
If the caller of this function deletes the pointer after it uses it, there is no leak. Therefore, it is not appropriate to comment on the memory leak given just this piece of code.
To refrain from such a case where the caller forgets to delete the object, use shared pointer, or another smart pointer.
Nope, all that does is pass back the pointer to Winsock. For example
Winsock* ws = CreateWinsock();
ws->doSomething();
//......
//some more stuff
//......
//Finished using Winsock
delete ws;
If the delete wasn't called there when you're finished with Winsock then that would be seen as a memory leak because memory would be taken up by Winsock when its not being used anymore.
Following class will be initiated with a member variable newTodayTaskString (string).
When destructing the object I like to delete the string but when compiling the project I get an error message pointing to the destructor delete line saying:
delete: std::string cannot be converted to void
Class:
class TodayTask {
private:
string newTodayTaskString;
public:
TodayTask (string t) : newTodayTaskString (t){}
// Destr.
~TodayTask () {
delete newTodayTaskString;
}
string getTodayTaskString () const {
return newTodayTaskString;
}
};
delete must be given a pointer, and can only be used to destroy objects created with new.
In this case, the object is a class member, and so will be destroyed automatically. You don't need to do anything with it in the destructor.
In c++, memory can be allocated either automaticaly or manualy.
If you define a simple variable, the memory for it is allocated automaticaly, in the Stack. The memory is then automatically freed. For example:
void foo()
{
std::string s;//memory is allocated here
}//the variable only lives inside the function, so at this point the memory is freed
The second way is to allocate the memory manualy, with the operator new, like this:
void foo()
{
int * i = new int();//we allocate the memory for our variable here.
}
Here, the memory is alocated in the heap, and it will not be freed automaticaly in the end of the funciton, or anywhere else until your programm ends.
In this case, you need to call operator delete, but you must call it only once for each variable:
void foo()
{
int * i = new int();
<...some code...>
delete i;//we free the memory at this point.
}
Note that if you will try to delete the same variable twice, you might get a segmentation fault.
In your case you are trying to manualy delete a variable for which you have not manually allocated the memory, which leads to the error. In your case you don't need to bother with the destructor, everything will be done automaticaly.
delete is only needed when the object is created using new. In this case, your object is automatically created before the constructor since it is a member variable. Thus, it is automatically destroyed after the destructor is called.
You should use delete only when you created it using new
You don't 'delete' newTodayTaskString, since it hasn't been allocated with 'new'. It's a member variable -- it will be automatically constructed and destructed, there's nothing you have to do.
You don't need to delete newTodayTaskString as it is not you who allocates its memory
You really don't have to delete the string. It's not dynamically allocated.
Just remember this:
use delete when you new something.
use delete[] when you new an array of something.