Search code examples
c++referencereturn-value-optimization

Returning local object of a primitive type and a struct


Getting a reference to temporary variable:

struct S
{
    S() = default;
    S(const S& other) = delete;
    S(S&& other) = delete;

    ~S(){}
};

S foo1()
{
    return {}; // RVO (???)
}

int foo2()
{
    return 42; // RVO
}

int main()
{
    S& i = foo1(); // compiles!
    int& i2 = foo3(); // error C2440: 'initializing' : cannot convert from 'int' to 'int &'
}

I know about reference life extension with const specifier. And it's clear why foo2 gives an error. But why foo1 works?

P.S.: tested with VS2013/15


Solution

  • Compiling with all warnings enabled (/Wall), you incidentally get the following:

    source_file.cpp(22): warning C4239: nonstandard extension used: 'initializing': conversion from 'S' to 'S &'