Suppose I have a class:
class ClassX{
private:
int* p;
int i;
....
}
And somewhere I do:
ClassX x;
.....
//and in a friend function or in a ClassX function
p = (int*) malloc (.....);
Then when x exit its scope a the destructor is invoked; but it does not free the memory allocated by the malloc right?
And if I redefine it:
ClassX::~ClassX(){ delete [] p; }
it frees the memory allocated by the malloc but not the memory allocated for the class’ fields (i.e. i and p)?
Am I missing something?
Thank you.
First of all, remember these things:
mallocneed to be deallocated byfreemallocnewmust be deallocated bydeletenew[]must be deallocated bydelete[]deletefor everynewand onedelete[]for everynew[]Then, you are correct in thinking that, without a destructor, the memory allocated by
mallocwill not be freed. If you follow the rules above, then you need to usefree(notdelete[]) to deallocate it:However, you shouldn’t be using
mallocin C++ first of all since it doesn’t call the constructors of objects, you should usenew:However, if you do that, you have to write a copy constructor, copy assignment operator, move constructor, and move assignment operator. So let’s look at an even better way:
Now you don’t even have to write a destructor, you can just let the smart pointer deal with it for you because it will automatically call
deleteon the thing you made withnewwhen it’s destructor is called. Which leads us to…Your other question:
That’s about 1/4 correct. Since
iandpare members of the class, they are automatically deallocated when the enclosing class is deallocated, and if they were classes themselves, their destructors would be called. So if you putdeletein your destructor, that takes care of the memory allocated bynew, andiandpare cleaned up automatically, and everything’s good. (You were only 1/4 correct because you used the wrong deallocation function.)This means that, if you use a smart pointer, the smart pointer’s destructor will be called when your object is destructed, and it will automatically deallocates what you allocated with
newfor you. So you don’t even need to worry about it.This is all assuming you really want to have a dynamic
intas part of your class. If you can though, you’d much rather store theintby value (not store a pointer to it) and that way you don’t have to mess with smart pointers, deallocation, or any of that other stuff.