为何处理临时对象时优先选用std::swap而非std::move?
关于拷贝交换惯用法与直接move临时对象的疑问
查阅拷贝赋值运算符相关文档时,我注意到文档针对如下签名的赋值运算符推荐使用拷贝交换惯用法:
class-name & class-name :: operator= ( class-name )
文档给出的示例实现如下:
A& operator=(A other) { std::cout << "copy assignment of A\n"; std::swap(n, other.n); std::swap(s1, other.s1); return *this; }
我对此感到疑惑:为什么这里要选择与临时对象交换值,而非直接将临时对象的值move出来?比如可以写成这样:
A& operator=(A other) { std::cout << "copy assignment of A\n"; n = std::move(other.n); s1 = std::move(other.s1); return *this; }
除此之外,我还见过在移动构造函数中使用交换操作的场景——明明这类场景下原对象很快就会被销毁,无需保留其值到作用域结束,但代码依然采用交换而非直接move:
dumb_array(dumb_array&& other) noexcept : dumb_array() // C++11起支持通过默认构造函数初始化 { swap(*this, other); }
我多次遇到这类针对即将销毁的对象使用交换的情况,但始终无法理解这种方式相较于直接对临时对象使用std::move有什么优势。
内容的提问来源于stack exchange,提问作者Aleksandr Medvedev
相关产品推荐
相关产品推荐

