gpt4 book ai didi

c++ - 关于析构函数中对象生命周期的说明

转载 作者:行者123 更新时间:2023-12-03 16:57:27 24 4
gpt4 key购买 nike

Another question引用 C++ 标准:

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 callstarts, or — the storage which the object occupies is reused orreleased."


这似乎意味着不允许从析构函数访问对象的成员。然而,这似乎是错误的,事实更像是 Kerrek SB 的回答中所解释的:

Member objects come alive before a constructor body runs, and theystay alive until after the destructor finishes. Therefore, you canrefer to member objects in the constructor and the destructor.

The object itself doesn't come alive until after its own constructorfinishes, and it dies as soon as its destructor starts execution. Butthat's only as far as the outside world is concerned. Constructors anddestructors may still refer to member objects.


我想知道在析构函数中是否可以将对象的地址传递给外部类,例如:
struct Person;
struct Organizer
{
static void removeFromGuestList(const Person& person); // This then accesses Person members
}

struct Person
{
~Person() {
// I'm about to die, I won't make it to the party
Organizer::removeFromGuestList(*this);
}

};
这对我来说似乎没问题,因为我认为对象的生命周期一直持续到析构函数完成之后,但是上述答案的这一部分让我怀疑:

The object itself doesn't come alive until after its own constructorfinishes, and it dies as soon as its destructor starts execution. Butthat's only as far as the outside world is concerned. Constructors anddestructors may still refer to member objects.

最佳答案

C++ 标准对于析构函数执行期间类成员的确切状态似乎确实有点自相矛盾。
但是,以下摘录自此 Draft C++ Standard可能会让您放心,您调用 removeFromGuestList函数应该是安全的(我添加的粗斜体格式):

15.7 Construction and destruction

1   For an object with a non-trivial constructor, referring to any non-static member or baseclass of the object before the constructor begins execution results inundefined behavior. For an object with a non-trivial destructor,referring to any non-static member or base class of the object afterthe destructor finishes execution results in undefined behavior.


尚不清楚(至少对我而言)的是,一旦析构函数开始执行,通过对被销毁对象的引用来引用这些类成员是否有效。也就是说,假设您的 Person类(class)有成员, ObjectType a , 指的是 person.a在您的 removeFromGuestList功能有效吗?
另一方面,而不是通过 *this作为它的论点,如果您将每个必需的成员作为“不同的对象”传递,那么您将是安全的;因此,将该函数重新定义为 removeFromGuestList(const ObjectType& a) (带有可能的附加参数)将是 完全安全的。

关于c++ - 关于析构函数中对象生命周期的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67002935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com