Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is move assignment via destruct+move construct safe?

Here's a very easy way to define move assignment for most any class with a move constructor:

class Foo {
public:
  Foo(Foo&& foo);                     // you still have to write this one
  Foo& operator=(Foo&& foo) {
    if (this != &foo) {               // avoid destructing the only copy
      this->~Foo();                   // call your own destructor
      new (this) Foo(std::move(foo)); // call move constructor via placement new
    }
    return *this;
  }
  // ...
};

Is this sequence of calling your own destructor followed by placement new on the this pointer safe in standard C++11?

like image 866
Bjarke H. Roune Avatar asked Oct 26 '12 18:10

Bjarke H. Roune


1 Answers

Only if you never, ever derive a type from this class. If you do, this will turn the object into a monstrosity. It's unfortunate that the standard uses this as an example in explaining object lifetimes. It's a really bad thing to do in real-world code.

like image 99
Pete Becker Avatar answered Sep 20 '22 03:09

Pete Becker