1

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; } 
9
  • 4
    Correct. It's a dangling reference, and the code has undefined behavior. Commented Aug 22, 2022 at 19:21
  • 1
    Yep, you're reading leftover data from a part of the stack that CAN get reused. The fact that it happens to work for you does not mean it will work on any other system, or even for you in the future.. That's the danger of undefined behavior. Commented Aug 22, 2022 at 19:22
  • 1
    That's right, big problem. You might want to declare get like 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. =) Commented Aug 22, 2022 at 19:25
  • 2
    @πάνταῥεῖ member function refererence qualification was introduced in C++11: stackoverflow.com/questions/47002799/… Commented Aug 22, 2022 at 19:30
  • 2
    @NathanOliver: That said almost nothing in the standard library uses it, so it's not unusual for people to overlook it. Commented Aug 22, 2022 at 19:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.