Functions and Operators
Team LiB
Previous Section Next Section

Functions and Operators

25. Take parameters appropriately by value, (smart) pointer, or reference.

Parameterize well: Distinguish among input, output, and input/output parameters, and between value and reference parameters. Take them appropriately.

26. Preserve natural semantics for overloaded operators.

Programmers hate surprises: Overload operators only for good reason, and preserve natural semantics; if that's difficult, you might be misusing operator overloading.

27. Prefer the canonical forms of arithmetic and assignment operators.

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.

28. Prefer the canonical form of ++ and --. Prefer calling the prefix forms.

If you ++c, also c++: The increment and decrement operators are tricky because each has pre- and postfix forms, with slightly different semantics. Define operator++ and operator-- such that they mimic the behavior of their built-in counterparts. Prefer to call the prefix versions if you don't need the original value.

29. Consider overloading to avoid implicit type conversions.

Do not multiply objects beyond necessity (Occam's Razor): Implicit type conversions provide syntactic convenience (but see Item 40). But when the work of creating temporary objects is unnecessary and optimization is appropriate (see Item 8), you can provide overloaded functions with signatures that match common argument types exactly and won't cause conversions.

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

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 violateItems 26 and 31), and this is a sure way to introduce subtle bugs and fragilities. Don't overload these operators naïvely.

31. Don't write code that depends on the order of evaluation of function arguments.

Keep (evaluation) order: The order in which arguments of a function are evaluated is unspecified, so don't rely on a specific ordering.

    Team LiB
    Previous Section Next Section