The function is well-formed (syntactically correct), but as soon as the function returns, the returned reference is invalid and cannot be used.
To clarify: the code in question does not invoke any undefined behavior. You can safely call this function so long as you do not use the return value, e.g., this is valid:
test_function(); // ok
However, if you try to use the return value (i.e., initialize another reference with it or copy the referent into another object) then you will invoke undefined behavior because the lifetime of the referent (the object x
) will have ended (x
will be destroyed when the function returns because it is an automatic variable):
std::vector<int>& vec = test_function(); // undefined
std::vector<int> vec = test_function(); // undefined