简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM