Home > Net >  Does the synthesized destructor destroy the memory allocated on the heap?
Does the synthesized destructor destroy the memory allocated on the heap?

Time:11-22

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

CodePudding user response:

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.

CodePudding user response:

As an additional answer to Anoop's correct one:

Just try to "emphasize" with the compiler and the runtime. If the destructor call occurs, how should the environment decide whether to call delete on a pointer or not? It has no chance to determine this and it's actually not its job by language design (partially in contrast to the C# and Java philosophy). The pointer could be a non-owning one as well, whose referred dynamically allocated storage should survive your particular destructor call, even possible for cases where your class was the allocator (bad design in general but allowed).

The destructor context just "sees" the members and for this case, that's solely a pointer a priori, not a possibly further dynamically allocated ressource. Please try to get familiar with the important RAII -technique, that is not only relevant to dynamic memory allocation.

  • Related