Search code examples
c++lambdaconst-reference

Return local variable to const ref from lambda


const TBigType& a = [](){
    TBigType result;
    // ...
    return result;
}();

use(a); // by const ref

Is it ok to capture result in const ref like this?


Solution

  • Your lambda returns a prvalue, so the call expression is a temporary object, whose lifetime is extended because it is bound to a reference.

    The situation is entirely analogous to the following, simpler example:

    int f() { return 12; }
    
    const int& a = f();
    

    Here a is bound to a temporary object of type int and value 12.

    If you do not specify the return type of a lambda, the return type is always either void or an object type. If you want your lambda to return an lvalue or xvalue, you will explicitly need to specify the return type, e.g. as -> int&, -> auto&, -> decltype(auto), etc.