移动构造函数与移动赋值
Move constructor vs. Move assignment
作为这个问题的扩展,我正在尝试使我的移动作业正确。
我有以下代码:
// copy assignment operator
LinkedList<T>& operator= (LinkedList<T> other) noexcept
{
swap(*this, other);
return *this;
}
// move assignment operator
LinkedList<T>& operator= (LinkedList<T>&& other) noexcept
{
swap(*this, other);
return *this;
}
但是当我尝试使用它时,我的代码无法编译。
首先是一些代码:
LinkedList<int> generateLinkedList()
{
LinkedList<int> List;
List.add(123);
return List;
}
int main()
{
LinkedList<int> L;
L = generateLinkedList();
^ get an error here...
我收到以下错误:
main.cpp(24(: 错误 C2593:"运算符 ="不明确
linkedlist.h(79(:注意:可以是"LinkedList &LinkedList::operator =(LinkedList &&( noexcept'(指向移动赋值运算符(
linkedlist.h(63(:注意:或 'LinkedList &LinkedList::operator =(LinkedList( noexcept' (指向复制赋值运算符(
main.cpp(24(: 注意:在尝试匹配参数列表"(链接列表,链接列表("时
我的移动分配运算符是错误的,还是我以错误的方式使用它?
复制赋值运算符将采用const LinkedList<T>& other
,而不是LinkedList<T> other
。
这
LinkedList<T>& operator= (LinkedList<T> other) noexcept
{
swap(*this, other);
return *this;
}
是使用复制和交换同时实现复制和移动分配的方式。通过重用复制和移动构造函数(other
是复制构造的或移动构造的(,您只需将this
与other
交换即可。other
在函数结束时死亡,带走了this
的旧状态。这个实现是完全没问题的,但是你不需要临时的第二个重载(这确实是模棱两可的(。
如果要为复制分配与移动分配提供单独的复制分配运算符,签名将是
// copy assignment operator
LinkedList<T>& operator=(const LinkedList<T>& other) noexcept
{
//...
}
// move assignment operator
LinkedList<T>& operator=(LinkedList<T>&& other) noexcept
{
//...
}
但是,由于您已经有了swap
和复制+移动构造函数,因此最好使用复制和交换。
PS:由于这些似乎是内联定义(即在类体内(,您可以跳过<T>
模板参数 - 在LinkedList
模板类定义中,编写LinkedList
会自动引用"当前实例化"(即LinkedList<T>
(。
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- 对 r 值使用移动赋值运算符时的异常
- 移动构造函数与移动赋值
- 为什么定义移动构造函数会删除移动赋值运算符
- C++中移动赋值运算符的继承
- 从自身内部替换 std::函数(通过将移动赋值到 *this?)
- 为什么对象可以"moved"甚至缺少移动构造函数和移动赋值运算符?
- 移动赋值运算符与复制赋值运算符
- 查找所有移动构造函数和移动赋值运算符(特别是那些没有"noexcept"的运算符)
- 移动构造函数和移动赋值运算符与复制省略
- CRTP 和复制/移动赋值/构造函数继承
- 在原始对象上使用惯用(例如 TBB 的 thread_enumerable_specific')移动赋值调用析构函数
- 未隐式声明的移动赋值运算符
- 如何使用继承(抽象基类)实现移动构造函数和移动赋值运算符
- 移动构造函数和移动赋值
- 未调用移动赋值运算符
- 移动赋值运算符和移动构造函数之间的区别
- 为什么同时使用一个赋值运算符处理复制和移动赋值效率不高
- 我应该删除智能指针的移动构造函数和移动赋值吗
- 如果成员具有非平凡的noexcept赋值运算符,则默认的移动赋值不能显式为noexcept