通过移动分配从算术运算符过载中返回const值
Returning const value from arithmetic operator overload with move assignment
假设我有以下最小示例类:
#include <iostream>
class Foo {
public:
Foo() = default;
Foo(const Foo&) = default;
Foo(Foo&&) noexcept = default;
Foo& operator=(const Foo& rhs) {
std::cout << "copyn";
return *this;
}
Foo& operator=(Foo&& rhs) noexcept {
std::cout << "moven";
return *this;
}
Foo operator+(const Foo& rhs) const {
Foo x; // with some calculation
return x;
}
};
int main() {
Foo a, b, c;
a = b + c;
}
这将按预期打印move
。现在根据有效的C 项目3,我应该从operator+
返回const Foo
,以避免像a + b = c
这样的构造,即:
// To avoid a + b = c
const Foo operator+(const Foo& rhs) const {}
不幸的是,这突然开始调用复制分配而不是移动分配运算符。[我在Ubuntu上使用GCC 4.8.4,但它可能与编译器无关]
我如何确保a + b = c
无法编译,同时又调用a = b + c
的移动分配?或者随着移动语义的引入,是否可以同时实现这两个?
我最终使用了caninonos在评论中指出的LVALUE参考预选赛,而Max66现在已删除答案(但是10K用户可以看到(。
>Foo& operator=(const Foo& rhs) & {}
Foo& operator=(Foo&& rhs) & noexcept {}
实现很容易实现,它提供了更好的接口设计,因为分配了lvalue听起来没有有意义的其他任何内容。
。但是,应该注意的是,错误地编写a + b = c
的可能性非常低。编译器生成的分配运营商也不是LVALUE参考资格,我们可以使用标准类型编写a + b = c
,例如使用std::string
或使用std::complex
。
相关文章:
- 从函数返回const char*数组
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 从内部使用静态 std::string 的函数返回 const char * 是否安全?
- 从类方法返回 "const char*" 作为 std::string&
- 为什么const rvalue合格的std ::可选:: value()返回const rvalue参考
- 通过移动分配从算术运算符过载中返回const值
- 从本机代码返回"const char*"并在java中获取"字符串"
- 为什么我的C 函数拒绝返回const引用
- 通过参考返回和const函数返回const值的函数之间的差异
- 如果我返回const定义的对象,为什么const关键字被取消资格
- 返回const lvalue引用rvalue临时?为什么这项工作
- 内置类型的返回const值
- 返回 const std::string*& from a std::string *tab[11]
- 如何在静态方法中返回const类型
- 返回const引用和非常数成员函数调用
- 为什么不允许我将函数返回 const char* 的结果分配给 char*,bt 可以将字符串文字(常量)分配给 cha
- 在 C++ 中返回 const 字符串引用的字符串文本
- 为什么我们必须从一元前缀运算符重载返回 const 引用
- 在返回 const 错误的函数中传递值
- 为什么我可以将返回 'const T&' 的函数的返回值分配给 'T' 变量,而不是 'T&' 变量?