How can a returned object be assignable?

冷暖自知 提交于 2019-11-27 13:46:21

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/8832304/how-can-a-returned-object-be-assignable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!