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?
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.
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.
free() frees memory but doesn't call Destructor of a class whereas “delete” frees the memory and also calls the Destructor of the class.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With