开发者

Why return const Rational rather than Rational

开发者 https://www.devze.com 2023-01-21 14:02 出处:网络
I saw the following implementation of the operator* as follows: class Rational { public: Rational(int numerator=0, int denominator=1);

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?


  1. So that you can't do something like Rational a, b, c; (a * b) = c;.

  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消