1

I noticed that creating a lambda then making a copy results in different behavior between statics declared in the lambda and captured by value mutables. Specifically, when the lambda is copied the state of the mutable is copied and becomes independent of the lambda it was copied from. However, the value of the static internal to the lambda shares state between the copies.

#include <iostream>

int main()
{
    int i = 0;
    auto f = [i]() mutable {
        static int h=0;
        std::cout << "mutable captured i by value=" << ++i << "  static h=" << ++h << std::endl;
    };
    f();       // mutable captured i by value=1  static h=1
    i = 10;    // This shows that, as expected, changes in i are ignored by fc
    auto fc = f;
    f();       // mutable captured i by value=2  static h=2
    f();       // mutable captured i by value=3  static h=3
    fc();      // mutable captured i by value=2  static h=4
}

From this I gather that copies of a lambda share the same execution code and any retained state but also that mutable captured values are not shared between duplicated instances of the same lambda even though they are retained between calls.

Is this behavior correct? I have found this about statics in lambdas but haven't run across this difference in state behavior.

1 Answer 1

1

static variables inside a lambda behave just the same as ones declared elsewhere.

Variables captured by value behave as nonstatic data members of the lambda closure type. By default these members are treated as const in the lambda body; the effect of mutable is to remove that const. But in any case, they behave as members such as in a user-defined class.

So, captures and static locals are simply different things. The latter are not affected by mutable.

Sign up to request clarification or add additional context in comments.

1 Comment

I've almost always used lambas that contained no state as a kind of locally declared function but it's really just a type acting like a function complete with local, per instance, captured variables and possibly statics that are shared amongst all the type instances. Makes perfect sense. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.