gpt4 book ai didi

c++ - 我可以在其析构函数中使用指向已析构对象的指针吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:01:46 26 4
gpt4 key购买 nike

我可以从其析构函数中的指针访问已销毁的对象是否定义了行为?对象是否保证仍然在那个指针位置并且可以访问?例如,在下面的代码中,我销毁了 a1,并在其析构函数中从指向 a1 的 a2 访问了 a1。

#include <iostream>

class A
{
public:
A(int* i) : m_i(i) {}
~A();
int* m_i;
};

A* a1;
A* a2;
int x = 0;

A::~A()
{
*a2->m_i = 1;
}

int main()
{
a1 = new A(&x);
a2 = a1;
delete a1;
std::cout << x << std::endl;
return 0;
}

最佳答案

这是个好问题。基本的答案是,当A对象的析构函数开始时,对象的生命周期结束,但是访问A对象的成员仍然是合法的(有一些限制)直到A 的析构函数完成。标准引用是:

[basic.life]/1:

... The lifetime of an object o of type T ends when: if T is a class type with a non-trivial destructor (15.4), the destructor call starts, ...

[basic.life]/6:

Before the lifetime of an object has started but after the storage which the object will occupy has been allocated41 or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that represents the address of the storage location where the object will be or was located may be used but only in limited ways. For an object under construction or destruction, see 15.7. ...

[class.cdtor]/2(,15.7/2):

... To form a pointer to (or access the value of) a direct non-static member of an object obj, the construction of obj shall have started and its destruction shall not have completed, otherwise the computation of the pointer value (or accessing the member value) results in undefined behavior.

因此,由于在执行对象*a2 的析构函数时发生对a2->m_i 的访问,因此它是允许的。 (注意 A::m_iA 的直接成员,因为A 没有基类。)

请注意(正如其他一些人已经指出的那样),存储 A 对象的内存在析构函数完成之前不会被释放。这就是 delete 表达式的工作方式。

关于c++ - 我可以在其析构函数中使用指向已析构对象的指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58454920/

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