【问题标题】:What is the difference between `void operator=(T&&)` and `T& operator=(T&&)`?`void operator=(T&&)` 和 `T& operator=(T&&)` 有什么区别?
【发布时间】:2021-04-16 01:24:38
【问题描述】:
class base 
{
public:
    base(const base&) = delete;
    base()
    {
        cout << "construct" << endl;
    }
    ~base() 
    {
        cout << "destruct" << endl;
    }

    int a;
    int b;

    /* The difference explanation I desired is here */
    void operator=(base&& other)  
    // base& operator=(base&& other) // this needs to collaborate with "return *this" 
    {
        this->a = other.a;
        this->b = other.b;
        // return *this;
    }

    /* Not here */
    base& operator=(base& other) = delete;
};

operator=(T&amp;&amp;) 的两个版本有什么区别?他们似乎都对我有用。但是,作为类成员函数,网站推荐base&amp; operator=(T&amp;&amp;)版本。

【问题讨论】:

  • 请将您的帖子限制在一个问题上。我建议将后半部分作为一个单独的问题发布。
  • 显示的两个重载之间的区别主要不在于它们返回的内容,而在于它们作为参数的内容。采用base&amp;&amp; other(右值引用)的那个是移动赋值运算符。采用base&amp; other(左值引用)的那个是复制赋值运算符。移动赋值操作符可以——而且通常确实——也可以返回base&amp;,没有充分的理由让它成为void
  • 两者的用法不同。返回base &amp; 的复制分配表单(如果未删除)可以链接,例如x = y = z 其中xyz 都是base 类型。返回 void 的移动分配不能被链接。具有返回 void 的移动分配和删除的副本分配的最终效果是,仅允许将临时变量作为右值的分配,并且不允许链接。
  • 赋值运算符可以返回任何有意义的值,包括void。期望它返回对对象本身的引用,但这不是必需的。对于某些课程,甚至作为团队的标准政策,可能有充分的理由“挑战现状”。

标签: c++ operator-overloading return-value assignment-operator


【解决方案1】:

在一种情况下,a=b=c 有效。另一方面,它没有。

就是这样。

传统上,a=b=c 执行b=c 然后将结果分配给a。如果您的operator= 返回void,则编译失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-10
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    相关资源
    最近更新 更多