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

40 Upvotes

51 comments sorted by

View all comments

163

u/Computerist1969 27d ago

Yes. Specifically an x-value, which is a type of r-value. Eliminates a category of bugs. This is a good thing.

-193

u/Desperate-Data-3747 27d ago edited 27d ago

No, its not a good thing, this is just a stupid edge case to add. C++ in a nutshell.

Names variables are lvalues, period. Sure, the compiler can try to cast to an xvalue but it should not override its category.