We all know that returning a reference to a local variable is a bad idea. However, I\'m wondering if it\'s ever really a good idea to a return a reference at all and if it\'s po
There are tons of good uses for returning a reference. One is, as you said, to emulate something like the native dereference operator:
struct Goo
{
int & operator[](size_t i) { return arr[i]; }
int & front() { return arr[0]; }
// etc.
private:
int * arr;
};
Another use case is when you return a reference to a thing that was passed in. The typical example is a chainable operation like <<
:
std::ostream & operator<<(std::ostream & os, Goo const & g)
{
return os << g[3];
}
As a final example, here's a thread-safe global object:
Goo & get_the_object()
{
static Goo impl;
return impl;
}
References are an integral part of the language, and they may well be returned by a function call. As you said, it's important to understand the lifetime of objects, but that's always true and not a particular problem of returning references.
Personally, I like returning references to static variables when I want to implement the Singleton pattern
SomeClass& getTheSingleton()
{
static SomeClass theInstance;
return theInstance;
}
I dont have to write any logic involving whether or not some pointer is initialized, and it gives me some control over the order of static initialization