Once programmers grasp the efficiency implications of pass-by-value for objects (see Item 20), many become crusaders, determined to root out the evil of pass-by-value wherever it may hide. Unrelenting in their pursuit of pass-by-reference purity, they invariably make a fatal mistake: they start to pass references to objects that don’t exist. This is not a good thing. For example:
1 | class Rational |
In the code above, we defined operator* returning a const reference of Rational instead of a const value of Rational which is what you should do. Because result is a local object which is destroyed when the function exists.
The same rule applies to a pointer to a local stack object, a reference to a heap-allocated object or a pointer or reference to a local static object. Think twice before returning a reference of these objects, most of time it will give you trouble.