First of all, remember these things:
- Things allocated by
malloc
need to be deallocated by free
- Don't use
malloc
- Things allocated by
new
must be deallocated by delete
- Things allocated by
new[]
must be deallocated by delete[]
- One
delete
for every new
and one delete[]
for every new[]
- Don't use any of the above
Then, you are correct in thinking that, without a destructor, the memory allocated by malloc
will not be freed. If you follow the rules above, then you need to use free
(not delete[]
) to deallocate it:
ClassX::~ClassX() { free(p); }
However, you shouldn't be using malloc
in C++ first of all since it doesn't call the constructors of objects, you should use new
:
ClassX::ClassX() : p(new int) { }
// NOW we use delete since we used new (not delete[] since we didn't use new[])
ClassX::~ClassX() { delete p; }
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:
class ClassX{
private:
ClassX();
std::unique_ptr<int> p;
int i;
....
};
// we have to break rule #6 here
ClassX::ClassX() : p(new int) { }
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 delete
on the thing you made with new
when it's destructor is called. Which leads us to...
Your other question:
it frees the memory allocated by the malloc but not the memory allocated for the class' fields (i.e. i and p)?
That's about 1/4 correct. Since i
and p
are 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 put delete
in your destructor, that takes care of the memory allocated by new
, and i
and p
are 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 new
for you. So you don't even need to worry about it.
This is all assuming you really want to have a dynamic int
as part of your class. If you can though, you'd much rather store the int
by 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.