我使用c++编程语言13.6.2 std::swap来实现移动语义,其思想如下:
class deutscheSchweine{
public:
deutscheSchweine(){std::cout<<"DS\n";}
deutscheSchweine& operator=(const deutscheSchweine& other){
deutscheSchweine tmp;
swap(*this, tmp);
return *this;
}
deutscheSchweine(deutscheSchweine&& other){}
deutscheSchweine& operator=(deutscheSchweine&& other){
swap(*this, other);
return *this;
}
};
int main(){
deutscheSchweine ds;
deutscheSchweine ds2;
ds2 = ds;
上面的例子在调用赋值之后,我们可以使用移动语义来避免从临时复制,但这个例子导致递归地调用移动赋值。我的问题是,我们可以在移动语义中使用交换,但以某种适当的方式吗?
发布于 2015-11-29 02:42:26
通过交换实现复制分配是一个好主意,但是您忽略了一些细节。
您需要在某个时刻对每个单独的成员调用move。这可以通过调用swap(*this, other);
并实现swap
的特殊化来实现,通过直接在每个单独的成员上调用swap
,或者通过让std::swap
调用您的移动赋值操作符。
不应使用swap
实现移动分配。
我们已经有一个关于“复制并交换”习惯用法的很好的指南,这里是:What is the copy-and-swap idiom?
另请阅读Should the Copy-and-Swap Idiom become the Copy-and-Move Idiom in C++11?
最后,您想要的(假设您的成员对象设计正确)是:
class deutscheSchweine
{
public:
deutscheSchweine(){std::cout<<"DS\n";}
// defaulted move operations (member-wise moves)
deutscheSchweine(deutscheSchweine&& other) = default;
deutscheSchweine& operator=(deutscheSchweine&& other) = default;
// copy construction is defaulted (member-wise copies)
deutscheSchweine(const deutscheSchweine& other) = default;
// copy assignment uses copy-and-move for exception safety
deutscheSchweine& operator=(deutscheSchweine other)
{
return *this = std::move(other);
}
};
https://stackoverflow.com/questions/33974934
复制相似问题