I have a function that returns an rvalue reference.
auto function() -> int&& {
int x{10};
std::cout << x << std::endl; // to check the value of x
return std::move(x);
}
Now, when I use the following code:
std::cout << function() << std::endl;
std::vector<int> v;
v.push_back(function());
std::cout << v[0] << std::endl;
This results in the following output
10
0
It looks like even though function() returns an rvalue-reference, vector is pushing back a default constructed int.
Interestingly, if I have a code like this:
auto x = function();
v.push_back(std::move(x));
This works perfectly.
It appears that if I had simply returned a local variable from the function then RVO would have done a copy elision anyway. But since I am doing an explicity std::move() I am tripping off RVO resulting in a temporary variable being returned.
Now, in v.push_back(function()) I am calling the vector::push_back(T&&) function, results in referring to a reference to a temp variable. In this case it always tend to be 0 rather than a garbage (I am guessing that this is because of optimisation turned on).
However, if I try to capture the return value of function() in a local variable it works, presumably because the value of the temp variable created in the process of return value is copied over to this local variable. This does not look like an I got lucky with an undefined behaviour.