27. Prefer the canonical forms of arithmetic and assignment operators

Summary

If you a+b, also a+=b: When defining binary arithmetic operators, provide their assignment versions as well, and write to minimize duplication and maximize efficiency.

Discussion

In general, for some binary operator @ (be it +, -, *, and so on), you should define its assignment version such that a @= b and a = a @ b have the same meaning (other than that the first form might be more efficient and only evaluates a once). The canonical way of achieving this goal is to define @ in terms of @=, as follows:

image

The two functions work in tandem. The assignment form does the ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.