Operator Redirection - Return by link or return by copy

Consider the following code?

I was wondering if I changed it (the function body is still the same)

error_code& operator|=(const error_code &e)

to

error_code operator|=(const error_code &e)

Is there a potential error that may occur? The only difference that I see is the execution of an additional copy operation, besides this, without much difficulty.

So, should I just return by reference, or does it not matter?


class error_code {
public:
 error_code() : hi(0), lo(0) {}
 error_code(__int64 lo) : hi(0), lo(lo) {}
 error_code(__int64 hi, __int64 lo) : hi(hi), lo(lo) {}

 // How about return by copy?
 error_code& operator|=(const error_code &e) {
  this->hi |= e.hi;
  this->lo |= e.lo;
  return *this;
 }

 __int64 hi;
 __int64 lo;
};

error_code operator|(const error_code& e0, const error_code& e1) {
 return error_code(e0.hi | e1.hi, e0.lo | e1.lo); 
}

int main() {
 error_code e0(1);
 error_code e1(2);
 e0 |= e1;
}
+3
source share
2 answers

Is there a potential error that may occur?

Yes. This will no longer work as expected:

(ec |= x) = y;

Now this is a dumb piece of code, no doubt, but

  • it works for other types and
  • there may be other cases where it matters.

, error_code -, , , , :

(ec |= x).normalize();  // whatever "normalizing" error code means...
+13

, , , . : , . . , .

+1

Source: https://habr.com/ru/post/1784490/


All Articles