Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Chapter 31.  Return Value Lifetime


31.2. Why Return-by-Reference?

You may wonder why we should ever return by reference, given that it is so fraught with danger, as we've already seen (see sections 16.2, 20.6.1) and will see further in this chapter. Well, the reason we've used it a great deal in our discussions of shims has been that it affords us the ability to provide highly generalized code by using a fundamental type—for example, char const*—as our common type. Furthermore, since all of C++ is a wrapper to some degree, we eventually have to get down to the metal at some point—that's the reason std::basic_string has a c_str() method, after all—so there's no escaping these issues somewhere along the way.

The other reason, as we shall see in this chapter, is that it is more efficient than return by value, occasionally by a large margin.


      Previous section   Next section