dimanche 26 février 2017

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.

Aucun commentaire:

Enregistrer un commentaire