(I am aware of the fact that returning address/reference to a variable local to the function should be avoided and a program should never do this.)
Does returning a reference to a local variable/reference result in Undefined Behavior? Or does the Undefined Behavior only occur later, when the returned reference is used (or "dereferenced")?
i.e. at what exact statement (#1
or #2
or #3
) does code sample below invoke Undefined Behavior? (I've written my theory alongside each one)
#include <iostream>
struct A
{
int m_i;
A():m_i(10)
{
}
};
A& foo()
{
A a;
a.m_i = 20;
return a;
}
int main()
{
foo(); // #1 - Not UB; return value was never used
A const &ref = foo(); // #2 - Not UB; return value still not yet used
std::cout<<ref.m_i; // #3 - UB: returned value is used
}
I am interested to know what the C++ standard specifies in this regard.
I would like a citation from the C++ standard which will basically tell me which exact statement makes this code ill-formed.
Discussions about how specific implementations handle this are welcome but as I said an ideal answer would cite an reference from the C++ Standard that clarifies this beyond doubt.
Best Answer
Of course, when the reference is first initialised it is done so validly, satisfying the following:
The reference being returned from the function is an xvalue:
That means the following does not apply:
Additionally, even if we interpret the following to mean that an initialisation of a new reference "object" is performed, the referee is probably still alive at the time:
However, your initialisation of a new reference
ref
insidemain
quite clearly violates[C++11: 8.3.2/5]
. I can't find wording for it, but it stands to reason that the function scope has been exited when the initialisation is performed.At the very least, there does not appear to be anything further stated about the matter in the standard, so if the above reasoning is not sufficient then we have to conclude that the standard is ambiguous in the matter. Fortunately, it's of little consequence in practice, at least in the mainstream.