Why return const Rational rather than Rational
I saw the following implementation of the operator* as follows:
class Rational {
public:
Rational(int numerator=0, int denominator=1);
...
private:
int n, d; // numerator and denominator
friend const Rational operator*(const Rational& lhs, const Rational& rhs)
{
return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
开发者_如何转开发 }
};
I have two questions here:
- Q1> why the operator* has to return const Rational rather than simply Rational
- Q2> when we define a friend function, should we care about the access modifier?
So that you can't do something like
Rational a, b, c; (a * b) = c;
.No.
Note that returning const Rational
instead of Rational
not only prevents nonsensical assignments but also move semantics (because Rational&&
does not bind to const Rational
) and is thus not recommended practice anymore in C++0x.
Scott Meyers wrote a note on this matter:
Declaring by-value function return values const will prevent their being bound to rvalue references in C++0x. Because rvalue references are designed to help improve the efficiency of C++ code, it's important to take into account the interaction of const return values and the initialization of rvalue references when specifying function signatures.
精彩评论