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; }
getlike this:int& get() & { return field; }and then it can only be called on lvalues, and will help prevent such mistakes at compile time. (But with field being a public data member, it doesn't offer much protection. =)