了解const运算符 [英] Understanding const operator

查看:127
本文介绍了了解const运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Scott Meyers的书,并遇到以下示例:

I'm reading Scott Meyers' book and come across the following example:

class Rational { ... };
const Rational operator*(const Rational& lhs, const Rational& rhs);

Rational a, b, c;
...
(a * b) = c; // invoke operator= on the
// result of a*b!

他说这是真的很奇怪的东西,但我不明白为什么。在 a * b

He said that it was really wierd thing, but I didn't see why. What's wrong with the invokation of the operator= on the result of a*b?

推荐答案

a * b 的结果是一个临时值,声明。分配给它是很奇怪,因为你不能在任务后做任何事情。

The result of a*b is a temporary value, which will disappear at the end of the statement. Assigning to it would be weird, since you wouldn't be able to do anything with it after the assignment.

但是,它的奇怪的事实不一定是正当的添加更多的奇怪,以防止它。在现代C ++中,返回一个 const 对象是一个坏主意,因为它禁止了移动语义。

However, the fact that it's weird doesn't necessarily justify adding more weirdness to prevent it. In modern C++, it's a bad idea to return a const object like this since it inhibits move semantics.

这篇关于了解const运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆