Note: OP and the other answers suggest variations on returning a pre-existing object (global, static
in function, member variable). This answer, however, discusses returning a variable whose lifetime starts in the function, which I thought was the spirit of the question, i.e.:
how can we return a variable by reference while the scope of the returning function has gone and its vars have been destroyed as soon as returning the var.
The only way to return by reference a new object is by dynamically allocating it:
int& foo() {
return *(new int);
}
Then, later on:
delete &myref;
Now, of course, that is not the usual way of doing things, nor what people expect when they see a function that returns a reference. See all the caveats at Deleting a reference.
It could make some sense, though, if the object is one of those that "commits suicide" later by calling delete this
. Again, this is not typical C++ either. More information about that at Is delete this allowed?.
Instead, when you want to return an object that is constructed inside a function, what you usually do is either:
- Return by value (possibly taking advantage of copy elision).
- Return a dynamically allocated object (either returning a raw pointer to it or a class wrapping it, e.g. a smart pointer).
But neither of these two approaches return the actual object by reference.