Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the order of destruction for data member matter?

Tags:

c++

I see in some book that the destruction order of data members in class should be in the reverse order of their construction order. What is the reason of this rule? Any examples are appreciated.

like image 748
Thomson Avatar asked Jan 15 '11 02:01

Thomson


1 Answers

This is, in large part, for consistency. When multiple objects are created in sequence, they are always destroyed in the reverse order. For example, consider the following example with automatic variables:

{ 
    A a;
    B b(a);
}   // b.~B() is called, then
    // a.~A() is called

Here, b uses a. By guaranteeing objects are destroyed in reverse order of their construction, C++ makes object lifetime management much easier.

In a class, you can pass a reference to one data member when you initialize another data member. Ensuring that objects are destroyed in reverse order, you get the same behavior as with automatic variables:

struct S
{
    A a;
    B b;

    S() : a(), b(a) { }
};

Note that it's usually not a good idea to have data members referring to each other, but it's both possible and occasionally useful.

like image 134
James McNellis Avatar answered Sep 26 '22 03:09

James McNellis