Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does the synthesized destructor destroy the memory allocated on the heap?

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading