Search code examples
c++memory-managementdestructorraii

Why the Destructor in C++ de-allocated memory in reverse order of how they were initialised?


What is the advantage in de-allocating memory in reverse order to variables?


Solution

  • 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, Object2s destructor accesses Object1's internal resource. If it weren't for the guarantee of reverse order of destruction, this would lead to problems.