这是后续这个问题。假设我有这样的代码:
class Class {
public virtual method()
{
this->~Class();
new( this ) Class();
}
};
Class* object = new Class();
object->method();
delete object;
这是一个简化版本这个答案建议。
现在一旦从内部调用析构函数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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)