Is assignment forwarding a safe destruct + move method?

Here's a very simple way to determine the move destination for most classes with the 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 and then the new location of this safe pointer in standard C ++ 11?

+7
source share
2 answers

Only if you never, never derive a type from this class. If you do this, it will turn the object into a monster. It is sad that the standard uses this as an example to explain the life of objects. This is really bad in real code.

+6
source

Technically, the source code is safe in this tiny example. But the reality is that even if you look at Foo funny, you will call UB. It is so terribly dangerous that it is completely not worth it. Just use swap, like everyone else - there is a reason for this, and this is because it is the right choice. Also, homing checks are bad.

0
source

All Articles