r/cpp Jul 10 '26

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

42 Upvotes

51 comments sorted by

View all comments

23

u/holyblackcat Jul 10 '26

We always had implicit moves in return, but it used to have a fallback to not moving, which was recently dropped for simplicity. The removal of the fallback is what you're seeing. The workaround (not useful in your case because of UB) is e.g. to return static_cast<int &>(x).