Returning "const T" from "T :: operator + (const T & rhs) const" good practice?

I often see my teachers use const operator +-*/

that return value const

. Is this good practice? Do I have to do this for every class I write? ( T

means any structure / class that overloads the + - * / operator).

For example:

struct Fraction
{
    //something here.
    const Fraction operator+(const Fraction &rhs) const;
    const Fraction operator-(const Fraction &rhs) const;
    const Fraction operator*(const Fraction &rhs) const;
    const Fraction operator/(const Fraction &rhs) const;
};

      

+3


source to share


2 answers


No, this is a bad idea as it interferes with move semantics. In the following:

a = b + c;

      



the temporary result b + c

can be carried over a

if not const

, but it must be copied if it is const

. Copying is often more costly than moving.

Historically, in the days before move semantics it has been suggested to prevent meaninglessness like (a + b) = c

. Some have argued that it would be better to make this cause a compile-time error rather than strange run-time behavior. These days, even if you agree with this argument, it has to do with cost.

+5


source


const

not required for return type (in general and in this case). The return is an rvalue, changing it might make sense, it might not, but in general, return types (by value) are not const

. This contrasts with the returned links, where it const

can make a difference.

Assuming C ++ 11 is in use, the return type const Fraction

will interfere with normal move semantics .

Considering overload arithmetic operators ( +

, -

, *

and /

), following the canonical form built-in operators. Returns the result for the modified value of r, i.e. Not const

. For the assignment versions of these operators ( +=

, -=

, *=

and /=

), return the value of the link (usually it is *this

).



Properly:

T T::operator+(const T2 &b) const;
// and
T& T::operator+=(const T2& b);

      

const

in member methods it makes sense here
, the object itself will not be modified (in a general sense), so it is recommended to mark them as const

.

+2


source







All Articles