I have a class without a destructor and a constructor like this:
class Foo {
public:
Foo(int a) : p(new int(a)) {}
private:
int *p;
};
{
Foo a(4);
}
After this block of code will the memory allocated on the heap be released ? Or do i have to explicitly provide a destructor like this:
class Foo {
public:
Foo(int a) : p(new int(a)) {}
~Foo();
private:
int *p;
};
Foo::~Foo() {
delete p;
}
Any memory we allocate on the heap using new
must always be freed by using the keyword delete
.
So,you have to explicitly free the memory allocated by new
on the heap using the keyword delete
as you did in the destructor. The synthesized destructor will not do it for you.
Note if you don't want to deal with memory management by yourself then you can use smart pointers. That way you will not have to use delete
explicitly by yourself because the destructor corresponding to the smart pointer will take care of freeing up the memory. This essentially means if the data member named p
was a smart pointer instead of a normal(built in) pointer, then you don't have to write delete p
in the destructor of your class Foo
.