在C ++ 11中应该返回temp返回const或非const的函数

时间:2014-01-10 03:21:55

标签: c++11 move-semantics

在移动构造函数之前如果返回了一个temp,最好让它返回const以避免让某人分配给temp变量

现在似乎移动构造函数不能处理const返回,似乎不返回const将是最佳实践

但是,现在你回到了某人合法分配给临时变量的问题

快速示例(假设一个非常昂贵的复制构造器):

MyClass a=1;
MyClass b=2;

(a+b)=3;  // how do I disallow this and allow move constuctors for `operator+`

如果operator+返回const MyClass那么它将无法编译,但任何常规用法都会使用昂贵的复制构造函数而不是廉价的移动构造函数。

1 个答案:

答案 0 :(得分:5)

通过约束赋值运算符只能处理左值:

,可以避免赋值给rvalues
class MyClass {
  MyClass& operator = (const MyClass& other) & {
    // ...
    return *this;
  }
  MyClass& operator = (MyClass&& other) & {
    // ...
    return *this;
  }
  // or, ideally:
  MyClass& operator = (const MyClass& other) & = default;
  MyClass& operator = (MyClass&& other) & = default;
};

Ref-qualifiers最近被添加到C ++ 11中,因此最近才开始出现编译器支持。