开发者

Why does the order of destruction for data member matter?

开发者 https://www.devze.com 2023-02-04 03:21 出处:网络
I see in some book that the destruction order of data members in class should be in the reverse order o开发者_如何学编程f their construction order. What is the reason of this rule? Any examples are ap

I see in some book that the destruction order of data members in class should be in the reverse order o开发者_如何学编程f 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.


I think maybe you've misunderstood. It's not that members should be destroyed in this order, but that they are specified to.

It can be important in rare circumstances to know the order that items are destroyed.

At any rate, that's the order that objects are destroyed in, there's nothing you can do about it but know that it's what is happening.


Lifetimes in C++ are nested as much as possible. It is possible, though usually rare, for data members to depend on each other directly (e.g. pass a pointer of one to another) or indirectly (e.g. both depend on a global, like writing output to stderr), but even when they don't, it's nice to have a specified order, and nesting fits better with how the rest of the language works (e.g. lifetimes at function scope) than other orderings would.

Of course, following the "as-if" rule in the standard, if the compiler/implementation can determine user code cannot observe destruction reordering, then it can do as it likes.

0

精彩评论

暂无评论...
验证码 换一张
取 消