1

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!

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?

2
  • 2
    There's nothing wrong with doing that, but it's very likely not to be intended. So this is a question of how much you want to help the programmer avoid silly mistakes. Commented May 27, 2015 at 16:19
  • 1
    @Kerrek y u write answer in comments Commented May 27, 2015 at 16:22

2 Answers 2

7

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.

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.

Sign up to request clarification or add additional context in comments.

7 Comments

So it's not an lvalue. Why could it appear at the left hand side of the = operator ever?
@St.Antario: Because, for class types like this, operator=() is a member function, and you can call member functions on rvalues.
@St.Antario: The restriction to have lvalues on the LHS of = applies to the built-in = operations (i.e. not operator= calls in user-defined types), not to literally any utterance of the symbol.
coliru.stacked-crooked.com/a/7d10a8c5cf66d504 Couldn't you explain what compiler's trying to say by that message. error: passing 'const Rational' as 'this' argument discards qualifiers I was confused by discarding qualifiers...
@St.Antario: It means the assignment is trying to call the non-const member function operator=() on a const object - doing so would discard the const qualifier, which isn't allowed. The const prevents the assignment, which is why Meyers suggested it (long before move semantics made it a bad idea).
|
2

What is wrong or weird is that the operator= is invoked on a object which will be destructed at the end of the statement (ie at ;).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.