Don't Return a Reference to an Object That Isn't in Scope!

After C++ programmers learn to pass by reference, they have a tendency to go hog-wild. It is possible, however, to overdo it. Remember that a reference is always an alias that refers to some other object. If you pass a reference into or out of a function, be sure to ask yourself, “What is the object I'm aliasing, and will it still exist every time it's used?”

Listing 12.4 illustrates the danger of returning a reference to an object that no longer exists.

Listing 12.4. Returning a Reference to a Nonexistent Object
 0: // Listing 12.4 1: // Returning a reference to an object 2: // which no longer exists 3: #include <iostream> 4: 5: class SimpleCat 6: { 7: public: 8: SimpleCat (int age, ...

Get Sams Teach Yourself C++ in 24 Hours, Third Edition 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.