繁体   English   中英

移动构造函数与移动赋值

[英]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是复制构造的或移动构造的),您只需将thisother交换。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM