【发布时间】:2020-03-22 02:15:42
【问题描述】:
作为This 问题的扩展,我正在努力让我的移动分配正确。
我有以下代码:
// 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: 'operator =' 不明确
linkedlist.h(79):注意:可能是 'LinkedList &LinkedList::operator =(LinkedList &&) noexcept'(指向移动赋值运算符)
linkedlist.h(63): note: or 'LinkedList &LinkedList::operator =(LinkedList) noexcept' (指向复制赋值运算符)
main.cpp(24): 注意:在尝试匹配参数列表时'(LinkedList, LinkedList)'
我的移动赋值运算符是错的,还是我用错了?
【问题讨论】:
-
What is the copy-and-swap idiom? 的第一个答案的 C++11 部分中有很好的解释。甚至可能已经足够好了。
标签: c++ move-assignment-operator