C++ 移动构造函数与移动赋值
作为问题的延伸,我正在努力使我的搬家作业正确无误 我有以下代码:C++ 移动构造函数与移动赋值,c++,move-assignment-operator,C++,Move Assignment Operator,作为问题的延伸,我正在努力使我的搬家作业正确无误 我有以下代码: // copy assignment operator LinkedList<T>& operator= (LinkedList<T> other) noexcept { swap(*this, other); return *this; } // move assignment operator LinkedList<T>& operator= (Linked
// 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&operator=(LinkedList其他)无例外
{
掉期(*本,其他);
归还*这个;
}
//移动赋值运算符
LinkedList和operator=(LinkedList和其他)无例外
{
掉期(*本,其他);
归还*这个;
}
但是当我尝试使用它时,我的代码无法编译
首先是一些代码:
LinkedList<int> generateLinkedList()
{
LinkedList<int> List;
List.add(123);
return List;
}
int main()
{
LinkedList<int> L;
L = generateLinkedList();
^ get an error here...
LinkedList生成器LinkedList()
{
链接列表;
增加(123);
退货清单;
}
int main()
{
链接列表L;
L=GenerateLinedList();
^在这里得到一个错误。。。
我得到以下错误:
main.cpp(24):错误C2593:“运算符=”不明确
h(79):注意:可以是'linkedlist&linkedlist::operator=(linkedlist&&)noexcept'(指向移动赋值运算符)
h(63):注意:或“linkedlist&linkedlist::operator=(linkedlist)noexcept”(指向复制赋值运算符)
cpp(24):注意:在尝试匹配参数列表(LinkedList,LinkedList)时
我的移动分配运算符是否错误,或者我是否使用了错误的方式?复制分配运算符将采用
常量LinkedList&other
,而不是LinkedList other
这个
但是,由于您已经有了swap
和copy+move构造函数,因此最好使用copy和swap
PS:由于这些似乎是内联定义(即在类主体中),您可以跳过
模板参数-在LinkedList
模板类定义中,写入LinkedList
自动引用“当前实例化”(即LinkedList
).复制分配运算符将采用常量LinkedList&other
,而不是LinkedList other
这个
但是,由于您已经有了swap
和copy+move构造函数,因此最好使用copy和swap
PS:由于这些似乎是内联定义(即在类主体中),您可以跳过
模板参数-在LinkedList
模板类定义中,写入LinkedList
自动引用“当前实例化”(即LinkedList
).在的第一个答案的C++11部分中有很好的解释。甚至可能足够好。在的第一个答案的C++11部分中有很好的解释。甚至可能足够好。现在我已经更新了复制赋值运算符以接收常量LinkedList&。现在它无法编译。我在()@tannic抱歉,我本来打算删除第二个代码段中的主体,因为它们没有意义。事实上,您不能使用const LinkedList&
(因为它是const
)进行交换-您必须先手动构造一个副本(即LinkedList副本(其他);交换(*此,副本);返回*此;
),但最好是以正常方式进行复制和交换。我不知道这个技巧。不过,我在实现移动构造函数时使用了运算符=(其他)
。@TanveerBadar如果您的类型已经有swap
,您可以将移动构造函数作为默认构造函数+swap(*此,其他)
(但也许有一个更有效的实现——默认构造然后交换一些普通的int
值是浪费精力的,你最好首先复制它)。@MaxLanghof:如果我查看上面的链接(copy/swap paradime),我会看到这个codesnip,它实际上就是我使用的:dumb\u数组和操作符=(dumb_array other)//(1){swap(*this,other);//(2)return*this;}
现在我已经更新了复制赋值操作符,以接收一个常量LinkedList&。现在它不会编译。我在()@tannic抱歉,我本来打算删除第二个代码段中的主体,因为它们没有意义。事实上,您不能使用const LinkedList&
(因为它是const
)进行交换-您必须先手动构造一个副本(即LinkedList副本(其他);交换(*此,副本);返回*此;
),但最好是以正常方式进行复制和交换。我不知道这个技巧。不过,我在实现移动构造函数时使用了运算符=(其他)
。@TanveerBadar如果您的类型已经有swap
,您可以将移动构造函数作为默认构造函数+swap(*此,其他)
(但也许有一个更有效的实现——默认构造然后交换一些普通的int
值是浪费精力的,你最好首先复制它)。@MaxLanghof:如果我查看上面的链接(copy/swap paradime),我会看到这个codesnip,它实际上就是我使用的:dumb\u数组和操作符=(dumb_array other)//(1){swap(*this,other);//(2)返回*this;}
LinkedList<T>& operator= (LinkedList<T> other) noexcept
{
swap(*this, other);
return *this;
}
// copy assignment operator
LinkedList<T>& operator=(const LinkedList<T>& other) noexcept
{
//...
}
// move assignment operator
LinkedList<T>& operator=(LinkedList<T>&& other) noexcept
{
//...
}