While investigating an unrelated (really) problem, I came across a bunch
of examples of a construct that I'm pretty sure shouldn't work, yet it
seems to be working. Am I misunderstanding this (is there some reason
this code should work)? This is all in code belonging to my employer,
written by another employee, so I can't quote a large enough chunk for
you to test. But I think the concepts are simple enough for someone to
answer based on the info I can provide.
An inline function declares a std::vector, initializes it, then returns
it. The calling function assigns that return value to a const&.
My understanding is that the return of the local object makes a
temporary copy of that object, which exists only during the calling
statement. So the reference is to that temporary object, which no
longer exists.
inline std::vector<int> get_vector()
{
std::vector<int> result;
... code to put contents into result ...
return result;
}
in some other function
std::vector<int> const& local_vector = get_vector();
unrelated code
read the contents from local_vector
What is the scope of the temporary vector that catches the return value
from the function? I thought that scope should be just that statement.
Could the scope be the rest of the {} containing the statement?
Is this code working just because of a lazy destructor (frees the
memory, but leaves the pointer and contents intact and nothing happens
to reallocate that memory soon enough to trash it)? Or is the
destructor really not called until later?