lundi 22 avril 2019

Do mutable lambdas have their own copies of captured values?

std::function<void()> create_function (args...)
{
    int x = initial_value (args...);

    return [x] () mutable
    {
        std::cout << x++ << std::endl;
    };
}

I discovered I need the mutable keyword on the lambda otherwise x is const.

If I call create_function multiple times, will the returned function objects each have their own copy of x or is it shared?

To clarify, If I wanted this kind of functionality pre-C++11, I would have to write a class to encapsulate the capture, in which case I would have a choice of making x a member variable or global/static. If x is const it wouldn't matter. How does the language specify the storage of x with respect to different instances of the lambda?

Aucun commentaire:

Enregistrer un commentaire