30. Avoid overloading &&, ||, or , (comma)

Summary

Wisdom means knowing when to refrain: The built-in &&, ||, and , (comma) enjoy special treatment from the compiler. If you overload them, they become ordinary functions with very different semantics (you will violate Items 26 and 31), and this is a sure way to introduce subtle bugs and fragilities. Don’t overload these operators naïvely.

Discussion

The primary reason not to overload operator&&, operator||, or operator, (comma) is that you cannot implement the full semantics of the built-in operators in these three cases, and programmers commonly expect those semantics. In particular, the built-in versions evaluate left-to-right, and for && and || also use short-circuit evaluation.

The built-in ...

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.