简体   繁体   English

了解const运算子

[英]Understanding const operator

I'm reading Scott Meyers' book and come across the following example: 我正在阅读Scott Meyers的书,并遇到以下示例:

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!

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的结果上对operator=的调用有什么问题?

The result of a*b is a temporary value, which will disappear at the end of the statement. a*b的结果是一个临时值,该值将在语句末尾消失。 Assigning to it would be weird, since you wouldn't be able to do anything with it after the assignment. 分配它很奇怪,因为分配后您将无法对其进行任何操作。

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. 在现代C ++中,返回这样的const对象是一个坏主意,因为它禁止移动语义。

错误或奇怪的是,operator =是在将在语句末尾(即; )处被破坏的对象上调用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM