c++ - 销毁并重新创建对象是否会使指向该对象的所有指针都无效?

标签 c++ pointers destructor object-lifetime

这是 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/

相关文章:

c++ - 基类和派生类之间的不同调试器指针地址

C 字符数组串联内存转储

c++ - 如何使用主参数添加更多堆栈?

c - 为什么类型在 C 中的这个值交换代码中不匹配?

c++ - 如何在两个线程之间共享公共(public)资源?

c# - 在析构函数中执行新进程

c++ - 对象在析构函数中的作用域

c++ - C++ 二叉树析构函数

c++ - 错误 : Cannot allocate an object

c++ - 在类模板实例化中携带类型信息