0

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?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
neuviemeporte
  • 6,310
  • 10
  • 49
  • 78
  • 4
    In C++11 you definitely want to return by non-const because it's an rvalue, so you might want to tag this [tag:C++03] specifically. – Mooing Duck Aug 23 '12 at 16:12
  • A `const Integer` can bind to a `const Integer &`, and so you're still eligible for copy elision. You are however no longer able to use move construction. – Kerrek SB Aug 23 '12 at 16:13
  • Looks like a duplicate of this (or at least my answer posted there, *answers* this question as well) : [Functions with return values (C++)](http://stackoverflow.com/questions/7376554/functions-with-return-values-c) – Nawaz Aug 23 '12 at 16:14

1 Answers1

2

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.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • 1
    Most obvious (to me) examples of classes with `operator+` and that can benefit from moves are `std::string` and `std::valarray`. So if your class is a bit like either of those then they're not rare enough to neglect. If your class just has self-contained data members like `int` then moves are no better than copies. – Steve Jessop Aug 23 '12 at 16:24