Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 571
vladon Avatar asked Jul 25 '26 04:07

vladon


1 Answers

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.

like image 187
Kerrek SB Avatar answered Jul 26 '26 21:07

Kerrek SB