This is a little subjective I think; I'm not sure if the opinion will be unanimous (I've seen a lot of code snippets where references are returned).
According to a comment toward this question I just asked, regarding initializing references, returning a reference can be evil because, [as I understand] it makes it easier to miss deleting it, which can lead to memory leaks.
This worries me, as I have followed examples (unless I'm imagining things) and done this in a fair few places... Have I misunderstood? Is it evil? If so, just how evil?
I feel that because of my mixed bag of pointers and references, combined with the fact that I'm new to C++, and total confusion over what to use when, my applications must be memory leak hell...
Also, I understand that using smart/shared pointers is generally accepted as the best way to avoid memory leaks.
Not only is it not evil, it is sometimes essential. For example, it would be impossible to implement the [] operator of std::vector without using a reference return value.
i think using reference as the return value of the function is much more straight forward than using pointer as the return value of the function. Secondly It would be always safe to use static variable to which the return value refer to.
I ran into a real problem where it was indeed evil. Essentially a developer returned a reference to an object in a vector. That was Bad!!!
The full details I wrote about in Janurary: http://developer-resource.blogspot.com/2009/01/pros-and-cons-of-returing-references.html
In general, returning a reference is perfectly normal and happens all the time.
If you mean:
That is all sorts of evil. The stack-allocated
i
will go away and you are referring to nothing. This is also evil:Because now the client has to eventually do the strange:
Note that rvalue references are still just references, so all the evil applications remain the same.
If you want to allocate something that lives beyond the scope of the function, use a smart pointer (or in general, a container):
And now the client stores a smart pointer:
References are also okay for accessing things where you know the lifetime is being kept open on a higher-level, e.g.:
Here we know it's okay to return a reference to
i_
because whatever is calling us manages the lifetime of the class instance, soi_
will live at least that long.And of course, there's nothing wrong with just:
If the lifetime should be left up to the caller, and you're just computing the value.
Summary: it's okay to return a reference if the lifetime of the object won't end after the call.