销毁并重新创建对象会使该对象的所有指针无效吗?

问题描述:

这是此问题的后续措施.假设我有以下代码:

This is a follow-up to this question. Suppose I have this code:

class Class {
    public virtual method()
    {
        this->~Class();
        new( this ) Class();
    }
};

Class* object = new Class();
object->method();
delete object;

此答案建议的简化版本.

现在,一旦从method()内部调用析构函数,对象生存期就会结束,并且调用代码中的指针变量object将变得无效.然后在同一位置创建新对象.

Now once a destructor is invoked from within method() the object lifetime ends and the pointer variable object in the calling code becomes invalid. Then the new object gets created at the same location.

这是否使指向调用中对象的指针再次有效?

Does this make the pointer to the object in the calling valid again?

这已在3.8:7中明确批准:

This is explicitly approved in 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;
}