Search code examples
c++lambdac++11forwardingrvalue-reference

std::forward of rvalue ref to lambda?


Consider the following two snippets:

Exhibit A:

template<typename CalcFuncT>
int perform_calc(CalcFuncT&& calcfunc)
{
    precalc();
    int const calc = calcfunc();
    postcalc();
    return calc;
}

int main()
{
    perform_calc([]{ return 5 * foobar_x() + 3; }); // toFuture
    perform_calc([]{ return 5 * foobar_y() - 9; }); // toPast
}

Exhibit B:

template<typename CalcFuncT>
int perform_calc(CalcFuncT&& calcfunc)
{
    precalc();
    int const calc = std::forward<CalcFuncT>(calcfunc)();
    postcalc();
    return calc;
}

int main()
{
    perform_calc([]{ return 5 * foobar_x() + 3; }); // toFuture
    perform_calc([]{ return 5 * foobar_y() - 9; }); // toPast
}

Diff:

    precalc();
-   int const calc = calcfunc();
+   int const calc = std::forward<CalcFuncT>(calcfunc)();
    postcalc();

What will be the difference (if any) between the generated code of these two pieces of code?

In other words what effect is the std::forward having in the above, if any?

Note this question is not asking what std::forward does in general - only what does it do in the above context?


Solution

  • The forward casts the lambda object to an xvalue prior to calling the operator()() on it. The lambda object's operator()() is not qualified with or overloaded on "&&" and so the forward should have no impact.