Previous Section  < Free Open Study >  Next Section

Leak #7

General confusion concerning the overloading of nonmodifying operators. A nonmodifying operator is an operator that does not affect any of its operands and evaluates to an object of the same type as the operands. Typical examples include the mathematical operators like addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). Relational operators are not considered nonmodifying, because they always evaluate to type boolean regardless of the data types being compared. In addition, assignment operators (e.g., =, +=, <<=) are not nonmodifying, because these operators affect their left-hand-side operand.

Memory leakage associated with incorrectly implemented, nonmodifying operators is the type of problem that either is nonexistent in an application or appears in almost every class. This discrepancy is due to the fact that it revolves around invalid assumptions about overloaded operators. The main issue involved with the implementation of nonmodifying operators revolves around the return value. For the sake of efficiency, a C++ developer may decide to return the evaluated result by reference instead of by value. (Recall that returning an object by value will implicitly call the copy constructor, costing runtime.) A first attempt at designing such an operation might be to build the evaluated result in a temporary variable and return it by reference. The Point example in the code here illustrates the fact that returning a local object by reference is an error since the memory associated with the reference is returned to the stack upon exit from the function. The caller is left with a returned reference to an invalid, deallocated object.

    Previous Section  < Free Open Study >  Next Section