Search code examples
c++move-semanticstemporaries

Why don't temporary return types of rvalue functors cause undefined behavior?


I'm new to rvalues and lvalues so please forgive me.

Say I have the following code:

int&& temp() { return 5400; }

int x = temp();

This code compiles just fine with MSVC. When I print out x, it prints 5400. Shouldn't this not be possible, since temp() returns a reference to a destroyed object?


Solution

  • It does cause undefined behavior because you are returning and accessing a reference to an object that is destroyed when the function returns, specifically a temporary int object materialized from the 5400 prvalue in the return statement to bind the reference in the return value to. Whether the return type is a (const) lvalue reference or a rvalue reference does not matter at all.

    Undefined behavior means that there are no guarantees on the behavior of the program. It seemingly working is one possible outcome when no guarantees are given, but so is any other outcome as well, and none can be relied upon.