[英]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): error C2593: 'operator =' 不明确
linkedlist.h(79): 注意:可以是 'LinkedList &LinkedList::operator =(LinkedList &&) noexcept'(指向移动赋值运算符)
linkedlist.h(63): note: or 'LinkedList &LinkedList::operator =(LinkedList) noexcept' (指向复制赋值运算符)
main.cpp(24): 注意:在尝试匹配参数列表时 '(LinkedList, LinkedList)'
我的移动赋值运算符是错误的,还是我使用错误的方式?
复制赋值运算符将采用const LinkedList<T>& other
,而不是LinkedList<T> other
。
这个
LinkedList<T>& operator= (LinkedList<T> other) noexcept
{
swap(*this, other);
return *this;
}
是如何使用copy-and-swap同时实现复制和移动赋值。 通过重新使用复制和移动构造函数( 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>
).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.