简体   繁体   English

为什么数据成员的破坏顺序很重要?

[英]Why does the order of destruction for data member matter?

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 . 这里, b使用a By guaranteeing objects are destroyed in reverse order of their construction, C++ makes object lifetime management much easier. 通过保证对象以其构造的相反顺序被销毁,C ++使对象生命周期管理变得更加容易。

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. C ++中的生命周期尽可能地嵌套。 It is possible, though usually rare, for data members to depend on each other directly (eg pass a pointer of one to another) or indirectly (eg 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 (eg lifetimes at function scope) than other orderings would. 虽然通常很少,但数据成员可以直接相互依赖(例如,将指针传递给另一个)或间接地(例如,两者都依赖于全局,例如将输出写入stderr),但即使它们不在t,拥有一个指定的顺序是很好的,并且嵌套更符合其他语言的工作方式(例如在函数范围内的生命周期),而不是其他顺序。

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. 当然,遵循标准中的“as-if”规则,如果编译器/实现可以确定用户代码无法观察破坏重新排序,那么它可以按照自己喜欢的方式进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM