Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ destructor: when the memory gets freed?

Tags:

c++

destructor

If I delete an object which causes its destructor to be called, does the memory get freed before or after the destructor has finished doing whatever there is in the function?

like image 724
bittersoon Avatar asked Jan 25 '11 11:01

bittersoon


People also ask

Does calling destructor free memory?

You should not explicitly call the destructor, since doing so won't release the memory that was allocated for the Fred object itself. Remember: delete p does two things: it calls the destructor and it deallocates the memory.

Does a destructor deallocate memory?

But destructors are most often used to manage memory. Memory management for automatic or local objects is scope-driven. The program automatically allocates and deallocates stack memory when an object comes into or goes out of scope.

Does free invoke destructor?

free() frees memory but doesn't call Destructor of a class whereas “delete” frees the memory and also calls the Destructor of the class.

Is a destructor called when the program ends?

Yes. If the program terminates gracefully the destructors are called to clean up . This can easily be observed either by attaching a debugger or putting a printf in the destructor.

Why destructor is used when delete is there?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.


1 Answers

Memory is only freed once the least derived class subobject has been destroyed. So if you have:

class Base {
};

class Derived : public Base {
public:
    ~Derived();
};

then first Derived is destroyed, then Base is destroyed and only then memory is deallocated.

like image 55
sharptooth Avatar answered Sep 18 '22 01:09

sharptooth