sha*_*oth 9 c++ pointers destructor object-lifetime
这是这个问题的后续行动.假设我有这个代码:
class Class {
public virtual method()
{
this->~Class();
new( this ) Class();
}
};
Class* object = new Class();
object->method();
delete object;
Run Code Online (Sandbox Code Playgroud)
这是这个答案所暗示的简化版本.
现在,一旦从method()对象生命周期内调用析构函数结束,并且object调用代码中的指针变量变为无效.然后在同一位置创建新对象.
这是否使指向调用对象的指针再次有效?
这在3.8:7中得到明确批准:
3.8对象寿命[basic.life]
7 - 如果在对象的生命周期结束后,在原始对象占用的存储位置创建了一个新对象,则可以使用指向原始对象的指针.操作新对象,如果:( 在这种情况下满足的各种要求)
给出的例子是:
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;
}
Run Code Online (Sandbox Code Playgroud)