Gle*_*aum 1 move-semantics c++11
在移动构造函数之前,如果返回了一个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+`
Run Code Online (Sandbox Code Playgroud)
if operator+返回const MyClass然后它将无法编译,但任何常规用法将使用昂贵的复制构造函数而不是廉价的移动构造函数.
您可以通过约束赋值运算符来仅使用左值来避免赋值给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;
};
Run Code Online (Sandbox Code Playgroud)
Ref-qualifiers最近被添加到C++ 11中,因此编译器支持最近才开始出现.