I found the blow code compiles, even though get is called on a temporary, and the returned reference refers to a field of a temporary. Since it's not being used to initialize a const reference, the temporary should be destroyed once int& x = Test(5).get();
executes, correct? Therefore, does this leave x
a dangling reference?
#include <iostream>
struct Test {
int field;
Test(int x) : field(x) {}
int& get() {
return field;
}
};
int main()
{
int& x = Test(5).get();
std::cout << x;
}