class MyClass
{
};
void foo
{
MyClass arr[10];
}
I want to know the order of destruction of array objects when function returns.
I read it More Effective C++ about it and it says that destructor are invoked in reverse order to that of constructor order as follows:
for(int i = 9 ; i >= 0 ;i--)
{
arr[i].MyClass::~MyClass();
}
Can anybody tell me the reason for it ?
[11.3] What's the order that objects in an array are destructed? In reverse order of construction: First constructed, last destructed.
When an object goes out of scope or is deleted, the sequence of events in its complete destruction is as follows: The class's destructor is called, and the body of the destructor function is executed. Destructors for nonstatic member objects are called in the reverse order in which they appear in the class declaration.
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).
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.
That's continuation of reverse order of destructor invokation filosophy of C++. When stack-allocated objects are destroyed it is done in reverse order to facilitate RAII. Although that is not really necessary for array elements (they are all constructed with the default constructors and any order of construction/destruction would do) the same is done with them just for consistency.
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