dimanche 19 juin 2016

C++11 Lambda Capture Confusion


For reasons associated with the circumstances I'm using them in, I declare lambdas in one object, copy them to a second object, and execute them from a static function of a third class.

This actually works, but I'm a little confused about captures.

This works as expected

auto getTagString = [](CControl* control) -> std::string {
            return std::string("An Immediate Tag");

As does this (g_tag_string is a global variable)

auto getTagString = [](CControl* control) -> std::string {
            return g_tag_string);

However this doesn't work (it crashes). The object where the lamda was created is still in existence, but the "this" passed to the lambda when it is run is 0xcdcdcdcd

auto getTagString = [this](CControl* control) -> std::string {
            return this->tag_string_;

Nor does this (it returns an empty string)

std::string tag_string = "A Tag"
auto getTagString = [=](CControl* control) -> std::string {
            return tag_string);

Now that last one has me particularly confused, because I thought that the "=" meant that the value was taken at the point the lambda was created.

Are the captures lost when the lambda is copied?


Aucun commentaire:

Enregistrer un commentaire