Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

c++ - How can a returned object be assignable?

In Effective C++, Item 3, Scott Meyers suggests overloading operator* for a class named Rational:

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

The reason for the return value being const-qualified is explained in the following line: if it were not const, programmers could write code such as:

    (a * b) = c;

or, more probably:

     if (a*b = c)

Fair enough. Now I’m confused as I?thought that the return value of a function, here operator*, was a rvalue, therefore not assignable. I take it not being assignable because if I?had:

    int foo();
    foo() += 3;

that would fail to compile with invalid lvalue in assignment. Why doesn’t that happen here? Can someone shed some light on this?

EDIT: I have seen many other threads on that very Item of Scott Meyers, but none tackled the rvalue problem I exposed here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The point is that for class types, a = b is just a shorthand to a.operator=(b), where operator= is a member function. And member functions can be called on rvalues.

Note that in C++11 you can inhibit that by making operator= lvalue-only:

class Rational
{
public:
  Rational& operator=(Rational const& other) &;
  // ...
};

The & tells the compiler that this function may not be called on rvalues.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...