0

I have question, in this case should I use reference to overload operator or shouldn't?

Everything works fine with and without reference.

Vector & operator +=( const Vector & v )
{
    this->x += v.x;
    this->y += v.y;
    return * this;
}
Vector operator +=( const Vector v )
{
    this->x += v.x;
    this->y += v.y;
    return * this;
}

So which option is better to use?

Damian
  • 43
  • 4

2 Answers2

4

Use the reference one. Otherwise you are creating an unnecessary copy. Learn more: pass by value or by reference.

Guaranteed copy elision since C++17 might occur, but nevertheless, stick to good practices.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
  • Copy elision might apply? – πάντα ῥεῖ Jun 23 '19 at 18:46
  • How can copy elision apply? Since `*this` is not running out of scope? `int x; int y = x+=1;` has to create a copy somewhere. – Quimby Jun 23 '19 at 20:20
  • 1
    Worse than that. If you string a bunch of assignments together like `a += b += c`, not returning a reference will not modify the original object as you would expect, since you are only working with a copy. –  Jun 23 '19 at 21:57
1

The convention, when overloading operator +=, is to return a non-const reference. This stems from how the += operator natively works with primitive types in C++. Although it's very, very unusual to see code like the following in C++, it's perfectly legal:

int x = 137;
(x += 42) += 161;

The above code is only meaningful if the expression (x += 42) evaluates to x itself as an lvalue. Consequently, you should return a reference to the underlying object.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065