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.
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.
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