samedi 22 juillet 2023

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 try(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;
    };
}

Aucun commentaire:

Enregistrer un commentaire