Skip to content

Latest commit

 

History

History
41 lines (31 loc) · 1.02 KB

14.14.md

File metadata and controls

41 lines (31 loc) · 1.02 KB

Suppose we have a class A defines as:

class A {
  friend A operator+(const A &, const A &);
public:
  A &operator+=(cosnt A &);
private:
  int i;
}

If we define operator+= to call operator+ as:

A &A::operator+=(const A &rhs) {
  *this = *this + rhs;
  return *this;
}

A operator+(const A &lhs, const A &rhs) {
  A sum = lhs;
  sum.i += rhs.i;
  return sum;
}

Then, operator+= would create an unnecessary tempoary object when calling operator+ and copy/move this temporary object to this.

If we define operator+ to call operator+= as:

A &A::operator+=(const A &rhs) {
  i += rhs.i;
  return *this;
}

A operator+(const A &lhs, const A &rhs) {
  A sum = lhs;
  sum += rhs;
  return sum;
}

Then, there will be no temporary object when calling operator+=, since it will call operator+= on all data members, which do not create any temporary object.

Thus, it is more efficient to define operator+ to call operator+=.