9 Class operations

 

This chapter covers

  • Choosing between operators and methods
  • Handling self-assignment and return value optimization
  • Cooperating with the compiler for class members
  • Deciding between explicit and implicit conversions
  • Prefix and postfix versions of increment and decrement operators

This chapter continues the discussion of how to use instances well. The concept of the class invariant is always in view, but these mistakes need to be addressed with a different focus than the previous chapters. This certainly does not mean that it is less important, only that the emphasis is broader, touching on areas that do not necessarily directly affect the state of an object.

The category of performance is frequently addressed in these mistakes, with several emphasizing this aspect by focusing on eliminating unnecessary temporary objects. These temporary objects occur when an intermediate step in an expression evaluation requires an intermediary object to hold the results of a partial evaluation, which will be used in further evaluation. Knowing when these temporaries are created and how to design a class to eliminate many of them significantly affects the number of constructor and destructor calls.

Other mistakes focus on misusing operators that affect common usage or performance. C++ provides a significant amount of flexibility for the developer, and this flexibility must be respected to avoid using features improperly.

9.1 Mistake 61: Misunderstanding variable shadowing

9.2 Mistake 62: Allowing duplication of unique objects

9.3 Mistake 63: Not coding for return value optimization

9.4 Mistake 64: Not returning a reference from copy assignment operators

9.5 Mistake 65: Forgetting to handle self-assignment

9.6 Mistake 66: Misunderstanding prefix and postfix forms

9.7 Mistake 67: Misleading implicit conversion operators

9.8 Mistake 68: Overusing implicit conversion constructors

9.9 Mistake 69: Focusing too much on standalone operators

9.10 Mistake 70: Failing to mark nonmutating methods constant

9.11 Mistake 71: Not properly marking class methods static

9.12 Mistake 72: Incorrectly choosing between member and nonmember functions

9.13 Mistake 73: Incorrectly returning strings from accessor methods