Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning with a Local Variable in a Function Template

In the example below the function template is returning with a local variable and it works as expected even though the return value is not a reference. Is there a lifetime extension scenario in here? "result" variable is a local one and compiler doesn't generate any messages, and the code works as well. I expect that it fails since a local variable is used in the return statatement but it works.

template <typename F>
auto foo(const F& f)
{
    return [f](const std::vector<double>& v)
    {
        std::vector<double> result(v.size());
        std::transform(v.begin(), v.end(), result.begin(), f);
        return result;
    };
}
like image 846
terto Avatar asked Aug 20 '26 06:08

terto


1 Answers

Is there a lifetime extension scenario in here?

No, not at all. The function returns a capture-by-value lambda (with no references to local variables). It carries its own data and is therefore 100% safe when it comes to lifetimes.

"result" variable is a local one

It won't even exist until the call operator of the returned lambda is invoked. It will then be a local variable - most probably elided out of existence by Named Return Value Optimization.

How does it store the result variable?

Exactly like as-if you created a local class with a member, instantiated it and returned the instance:

struct my_lambda {
    std::vector<double> operator()(const std::vector<double>& v) const {
        std::vector<double> result(v.size());
        std::transform(v.begin(), v.end(), result.begin(), f);
        return result;
    }
    F f;
};
like image 97
Ted Lyngmo Avatar answered Aug 22 '26 23:08

Ted Lyngmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!