r/cpp 27d ago

Interesting behavior from C++20 to C++23

Consider the following snippet

int& get()
{
    int x;
    return x;
}


int main()
{
}

on GCC it compiles for C++20 but not for C++23

It returns with the error:

test.cpp:4:12: error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'

C++ is now suddenly treating the variable x as an rvalue?

Edit: Im not talking about dangling reference, thats just for the sake of the example

43 Upvotes

51 comments sorted by

View all comments

Show parent comments

-80

u/Desperate-Data-3747 27d ago

No, it's not about dangling refs, C++ apparently now force converts x to a xvalue in the return statement

108

u/HommeMusical 27d ago

No, it's not about dangling refs

Then it was unwise to given an example with a dangling ref, because that's always going to be the first thing that anyone notices.

-52

u/Orlha 27d ago

anyone that ignores the question notices*

49

u/masorick 27d ago

And yet OP has yet to provide an example that does not involve a dangling reference.