【发布时间】:2017-09-08 04:02:40
【问题描述】:
通过使用Copy & Swap 习惯用法,我们可以轻松实现具有强大异常安全性的复制分配:
T& operator = (T other){
using std::swap;
swap(*this, other);
return *this;
}
但是,这要求 T 为 Swappable。如果std::is_move_constructible_v<T> && std::is_move_assignable_v<T> == true 感谢std::swap,则自动为哪种类型。
我的问题是,使用“复制和移动”习语有什么缺点吗?像这样:
T& operator = (T other){
*this = std::move(other);
return *this;
}
前提是您为 T 实现了移动分配,否则显然您最终会得到无限递归。
这个问题与Should the Copy-and-Swap Idiom become the Copy-and-Move Idiom in C++11? 的不同之处在于这个问题更笼统,并且使用移动赋值运算符而不是实际手动移动成员。这避免了在链接线程中预测答案的清理问题。
【问题讨论】:
-
我还会在这个问题中添加另一种方法来做
operator =与放置新:T& operator =(const T & other) { this->~T(); return * new(this) T(other); } -
如果你的移动构造函数抛出异常怎么办?这不会使复制和移动习语不安全吗?
-
@Raxvan 没有很强的异常安全性。
-
@EmilyL。好的,抱歉,我收回了我的重复标志。为防止其他人这样做,我建议您编辑您的问题并添加此内容。
标签: c++ c++11 move-semantics copy-and-swap