spraff
spraff

Reputation: 33445

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?

Upvotes: 1

Views: 82

Answers (1)

bolov
bolov

Reputation: 75924

mutable doesn't change if the captured values are value or reference. It only changes constness.

You specify if you want values (copies) or references in the lambda capture:

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

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

Lambda captures are always modeled as non-static data members, if that was your confusion.

Upvotes: 3

Related Questions