在调用析构函数之前对象的生命周期就结束了吗?
我不明白这一点:
3.8/1 “类型 T 的对象的生命周期在以下情况结束: — 如果 T 是具有非平凡析构函数 (12.4) 的类类型,则析构函数调用 开始,或者——对象占用的存储被重用或者 已发布。”
如果生命周期在析构函数开始之前结束,这是否意味着访问析构函数中的成员是未定义的行为?
我也看到了这句话:
12.7 “对于具有非平凡析构函数的对象,在析构函数之后引用该对象的任何非静态成员或基类 完成执行会导致未定义的行为。”
但它没有明确说明析构函数期间允许执行哪些操作。
I don't understand this:
3.8/1 "The lifetime of an object of type T ends when: — if T is a class type with a non-trivial destructor (12.4), the destructor call
starts, or — the storage which the object occupies is reused or
released."
If the lifetime ends before the destructor starts, doesn't that mean accessing members in the destructor is undefined behavior?
I saw this quote too:
12.7 "For an object with a non-trivial destructor, referring to any non-static member or base class of the object after the destructor
finishes execution results in undefined behavior."
But it doesn't make clear what's allowed during the destructor.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
希望不是:
来自 N3242 构造和破坏 [class.cdtor] /3
Hopefully not:
From N3242 Construction and destruction [class.cdtor] /3
对象的“生命周期”与对象的使用者相关,而不是对象本身。因此,一旦开始销毁,消费类就不应该尝试访问对象的成员。
The "lifetime" of an object is relevant for consumers of the object, not the object itself. Therefore a consuming class should not attempt to access members of an object once destruction has started.
不,没有问题:
成员对象在构造函数体运行之前就活跃起来,并且它们一直保持活动状态直到析构函数完成之后。因此,可以在构造函数和析构函数中引用成员对象。
对象本身只有在其自己的构造函数完成后才会激活,并且一旦其析构函数开始执行,它就会死亡。但这只是外界的看法。构造函数和析构函数仍然可以引用成员对象。
No, there's no problem:
Member objects come alive before a constructor body runs, and they stay alive until after the destructor finishes. Therefore, you can refer to member objects in the constructor and the destructor.
The object itself doesn't come alive until after its own constructor finishes, and it dies as soon as its destructor starts execution. But that's only as far as the outside world is concerned. Constructors and destructors may still refer to member objects.
“一生”并不是这个意思。它是标准中精确定义的术语,具有多种含义,但它可能并不具有您想象的所有含义。成员仍然可以在构造和析构期间使用,外部代码可以调用成员函数等等。
当然,客户端代码与析构函数同时调用成员函数有点奇怪,但并非闻所未闻,当然也不是语言所不允许的。特别是,当存在对
condition_variable::wait()
的未完成调用时,std::condition_variable
显式允许调用析构函数。它仅在析构函数启动后禁止对wait()
进行新的调用。"Lifetime" doesn't mean that. It is a precisely defined term in the standard that has a variety of implications, but it might not have all the implications that you would think. Members can still be used during construction and destruction, outside code can call member functions, etc, etc.
Granted, it's a bit odd for client code to call member functions concurrently with the destructor, but not unheard of and certainly not disallowed by the language. In particular,
std::condition_variable
explicitly allows the destructor to be invoked while there are outstanding calls tocondition_variable::wait()
. It only prohibits new calls towait()
after the destructor starts.