What is the advantage in de-allocating memory in reverse order to variables?
Objects are always destroyed in reverse order of their creation. The reason for reverse order is, an object created later may use the previously created object.
The body of an object's destructor is executed, followed by the destructors of the object's data members (in reverse order of their appearance in the class definition), followed by the destructors of the object's base classes (in reverse order of their appearance in the class definition).
Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.
A destructor only destroys and cleans up the object. It does not deallocate the memory.
Consider this example:
Type1 Object1;
Type2 Object2(Object1);
Suppose that Object2
uses some internal resources of Object1
and is valid as long as Object1
is valid. For example, Object2
s destructor accesses Object1
's internal resource. If it weren't for the guarantee of reverse order of destruction, this would lead to problems.
It's not just about deallocating memory, it's about symmetry in a broader sense.
Each time you create an object you are creating a new context to work in. You "push" into these contexts as you need them and "pop" back again later -- symmetry is necessary.
It's a very powerful way of thinking when it comes to RAII and exception-safety, or proving correctness w.r.t. preconditions and postconditions (constructors establish invariants, destructors ought to assert()
them, and in well-designed classes each method clearly preserves them).
IMHO, lack of this feature is Java's single biggest flaw. Consider objects whose constructors open file handles or mutexes or whatever -- Armen's answer brilliantly illustrates how this symmetry enforces some common-sense constraints (languages such as Java may let Object1 go out of scope before Object2 but Object2 keeps Object1 alive by reference counting) but there's a whole wealth of design issues that fall neatly into place when considered in terms of object lifetimes.
Lots of C++ gotchas explain themselves when you bear this in mind
goto
s can't cross initialisationsreturn
in any function (this only applies to non-RAII languages such as C and Java)etc etc...
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