这是 this question 的后续行动.假设我有这段代码:
class Class {
public virtual method()
{
this->~Class();
new( this ) Class();
}
};
Class* object = new Class();
object->method();
delete object;
这是什么this answer的简化版本建议。
现在,一旦从 method()
中调用析构函数,对象生命周期就会结束,调用代码中的指针变量 object
将变得无效。然后在同一位置创建新对象。
这是否使指向调用中对象的指针再次有效?
最佳答案
这在 3.8:7 中得到明确批准:
3.8 Object lifetime [basic.life]
7 - If, after the lifetime of an object has ended [...], a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object [...] can be used to manipulate the new object, if: (various requirements which are satisfied in this case)
给出的例子是:
struct C {
int i;
void f();
const C& operator=( const C& );
};
const C& C::operator=( const C& other) {
if ( this != &other ) {
this->~C(); // lifetime of *this ends
new (this) C(other); // new object of type C created
f(); // well-defined
}
return *this;
}
关于c++ - 销毁并重新创建对象是否会使指向该对象的所有指针都无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12512961/