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?