doug
doug

Reputation: 4289

Lambda state behavior differences between an internal static and a captured mutable

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.

Upvotes: 1

Views: 187

Answers (1)

Potatoswatter
Potatoswatter

Reputation: 137800

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.

Upvotes: 1

Related Questions