是通过destruct +移动构造安全吗? [英] Is move assignment via destruct+move construct safe?
本文介绍了是通过destruct +移动构造安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里是一个非常简单的方法来定义移动分配大多数任何类与移动构造函数:
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;
}
// ...
};
这个顺序是调用你自己的析构函数,然后在这个指针上放置新的安全的标准C + +11?
Is this sequence of calling your own destructor followed by placement new on the this pointer safe in standard C++11?
推荐答案
只有当你永远不会从这个类派生一个类型。如果你这样做,这将把对象变成怪物。不幸的是,标准使用这个例子来解释对象生命周期。在现实世界的代码中,这是一个非常糟糕的事情。
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.
这篇关于是通过destruct +移动构造安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文