Does destroying and recreating an object make all pointers to this object invalid?

后端 未结 6 1630
我寻月下人不归
我寻月下人不归 2021-01-11 23:46

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

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


        
6条回答
  •  渐次进展
    2021-01-12 00:10

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

    The example given is:

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

提交回复
热议问题