Move semantics and operator overloading

后端 未结 2 943
一生所求
一生所求 2021-01-31 12:52

This is related to this answer provided by Matthieu M. on how to utilize move semantics with the + operator overloading (in general, operators which don\'t re-assign directly ba

2条回答
  •  春和景丽
    2021-01-31 13:17

    I don't think you're missing anything -- the code in your question is indeed trouble. The earlier part of his answer made sense, but something was lost between the "four desired cases" and the actual example.

    This could be better:

    inline T operator+(T left, T const& right) { left += right; return left; }
    inline T operator+(const T& left, T&& right) { right += left; return right; }
    

    This implements the rule: Make a copy of the LHS (preferably via move construction), unless the RHS is expiring anyway, in which case modify it in place.

    For non-commutative operators, omit the second overload, or else provide an implementation that doesn't delegate to compound assignment.

    If your class has heavyweight resources embedded inside (so that it can't be efficiently moved), you'll want to avoid pass-by-value. Daniel makes some good points in his answer. But do NOT return T&& as he suggests, since that is a dangling reference.

提交回复
热议问题