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) {}
error_code& operator|=(const error_code &e) {
this->hi |= e.hi;
this->lo |= e.lo;
return *th开发者_StackOverflow中文版is;
}
__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;
}
I was wondering, whether I should make operator|=
to return a const error_code&
or error_code&
?
It should return non-const error_code&
. Generally, an overloaded operation/equals operator should mirror integral type semantics and return a non-const reference. The OR-equals operation is modifying the object, so it doesn't really make sense to return a const
reference. Returning a non-const reference also allows you to chain OR-equals operations, the same way you could do with an integral type.
Option 1: return a non-const reference. This would allow you to do the following:
error_code e1, e2, e3;
// same as: e1 = e3
(e1 = e2) = e3;
Option 2: return a const reference. This would produce an error on the given example above because you can't do compound assignment on e1
which is a const reference.
Which one to choose? I would say it is a hard question because native types of the language follow the first option but it is actually undefined behavior to do so. Taking the second option, would deviate from imitating the native types. I would return a const-reference if I were writing the class.
精彩评论