销毁并重新创建对象会使该对象的所有指针无效吗? [英] Does destroying and recreating an object make all pointers to this object invalid?

查看:118
本文介绍了销毁并重新创建对象会使该对象的所有指针无效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

这篇关于销毁并重新创建对象会使该对象的所有指针无效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆