【问题标题】:Should C++11 Move and Copy Assignment Operators return const?C++11 移动和复制赋值运算符应该返回 const 吗?
【发布时间】:2015-08-26 10:13:23
【问题描述】:

C++11 移动和复制赋值运算符应该返回 const 吗?

示例代码:

const my_class& operator=(const my_class& other)
{
    // Copy the data
    my_class tmp(other);
    *this = std::move(tmp);

    return *this;
}


const my_class& operator=(my_class&& other)
{
    // Steal the data
    std::swap(my_data_length, other.my_data_length);
    std::swap(my_data, other.my_data);

    return *this;
}

为了清楚起见:

class my_class
{

    protected:

    double *my_data;
    uint64_t my_data_length;
}

注意返回类型上的const。我通常会不假思索地提出这个问题,但真的有必要吗?返回const 会阻止您做什么? (这里有一个例子会很有帮助。)

请注意,给出了一个示例,但随后将其删除。任何人都可以评论以下内容吗? (a = b).non_const_member_function();

【问题讨论】:

    标签: c++11


    【解决方案1】:

    不,它们绝对不应该返回对 const 的引用。一个典型的声明是:

    my_class& operator=(const my_class& other)
    my_class& operator=(my_class&& other)
    

    根据cpprefernce:

    CopyAssignable

    MoveAssignable

    为复制和移动分配返回T& 是满足CopyAssignableMoveAssignable 概念的要求

    【讨论】:

      【解决方案2】:

      简短回答:不。

      赋值运算符和运算符,如+= e.t.c。应该总是返回对类的引用,以便可以再次分配它:

      如果它返回const,由于返回对象是不可变的,你不能执行以下操作。

      std::string str = "Hello";
      
      (str = "Hello World") += "!";//assign value to hello world then append !
      

      返回 const& 仍然允许您执行声明为 const 的函数,但不会修改容器,例如 =+=swap

      【讨论】:

        【解决方案3】:

        那么返回值可以用于链式赋值。所以一个 const 返回会阻止这样的系统:(a = b) = c。因为a=b 返回一个 const 对象。

        【讨论】:

        • a = b = c 表示a = (b = c),它仍然有效。当= 返回const 时,只有(a = b) = c 不起作用。
        • 他们从右到左分组(a = (b = c)),所以这不是重点
        • @hvd 代码(a = b) = c 实际上会做什么?将 b 分配给 a,然后呢?将 c 分配给 a?
        • 我的错误。更改分组。
        • 在这种情况下真的重要吗?因为如果此代码将 b 分配给 a,然后将 c 分配给 a,那么这本质上等同于将 c 分配给 a 而 b 不存在......所以在这种情况下,它是否编译真的很重要,因为肯定你永远不想做(a = b) = c?不过还是很有趣的例子。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-03
        • 2017-11-21
        • 1970-01-01
        • 1970-01-01
        • 2015-05-31
        • 2015-04-28
        • 2020-05-16
        相关资源
        最近更新 更多