Should the return value of binary operator+ overload be const and can it interfere with optimizations?
-
28-06-2021 - |
Pergunta
Given the example code:
class Integer
{
int i_;
public:
Integer(int i) : i_(i) {}
const Integer operator+(const Integer &arg) const { return Integer(i_ + arg.i_); }
};
I started wondering whether operator+() should actually return a const Integer or not. Bruce Eckel in "Thinking in C++" provides examples for operator overloading for a similar case and seems to favor the const modifier on the return type. Should it be used and why?
On the other hand, let's try to use this class:
int main()
{
Integer a(1), b(2);
Integer c = a + b;
}
When creating c as a sum of a and b the compiler will most likely perform copy elision and Integer::operator+() will create its result in the spot occupied by c (see "Want speed? Pass by value") directly. But when the return type of Integer::operator+() is declared const, won't that force the compiler to perform copying since the target is non-const?
Solução
Returning an Integer const
protects against things like:
(a + b) = c;
I've never found this to be too much of a problem, but forbidding it does make the type behave more like the built-in types. It shouldn't have any impact with regards to return value optimization.
If the class is extremely expensive to copy, and can be made to support
rvalue references effectively, you might want to avoid the const
because of these, but in practice, I suspect that such classes are rare
enough that you can afford to neglect them.