Is move assignment via destruct+move construct safe?

有些话、适合烂在心里 提交于 2020-01-02 01:55:11

问题


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?


回答1:


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.




回答2:


Technically, the source code is safe in this tiny example. But the reality is that if you ever even look at Foo funny, you will invoke UB. It's so hideously unsafe that it's completely not worth it. Just use swap like everybody else- there's a reason for it and it's because that's the right choice. Also, self-assignment-checking is bad.



来源:https://stackoverflow.com/questions/13092240/is-move-assignment-via-destructmove-construct-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!