C++ Returning Reference To Local Variable

30 Aug 2015

Functions are units that take several arguments as inputs and produce outputs. Outputs are values returned by functions. If values returned are primitive data types, the values are copied and assigned to a variable that holds the returned value. If values are objects, then a copy constructor is used to copy the content of the object being returned to a newly created object.

If the object being returned is a complex, big object, then the copying operation is expensive, and if the function returning such object is called very frequently, then very likely the program will slow down noticeably.

Thankfully, most of the compilers nowadays implements some form of Return Value Optimization , therefore copying operation does not happen while returning big objects. The idea behind RVO is actually quite simple: a value-result argument is passed as a function argument and set in the function.

If you don’t want to rely on compiler optimization, there is already an old idiom in C++ ready for this: binding a temporary object to a const reference. The life of local object created on the local stack of a function is extended until even after the function had returned! No copying is involved.

Another, newer approach to achieve the same thing in C++11 is by using std::move: A local object is moved to another scope. IMHO, this approach is more explicit and avoid the confusion that might arise when using the const reference binding.