简体   繁体   中英

Why can't a data member be in a lambda capture list

I have a class foo that has bar as a member variable.

In another member function of the class, I'm writing a lambda function:

[bar](void){}

But I can't include bar in the capture list. Why is that?

Only objects with automatic storage duration can be captured by a lambda in C++11 (ie local variables and function parameters). If you want the effect of capturing a non-static class data member, you can either capture the this pointer as in Danvil's answer :

auto f = [this]{ std::cout << a << std::endl; };

or cache the data member's value in a local variable and capture that:

auto a = this->a;
auto f = [a]{ std::cout << a << std::endl; };

which will be much more concise in C++14:

auto f = [a = this->a]{ std::cout << a << std::endl; };

The choice between these two options depends on whether you want to store the value a has right now or if you want to retrieve the value a has when the lambda is called . Note that in the case where this is captured you must ensure that the lifetime of the pointer object encloses the lifetime of the lambda a call to the lambda after the object is destroyed has undefined behavior. The more simple case that captures a copy of a is completely self-contained and has no such lifetime issues.

You capture class members by saying this in the capture list. This has nothing to do with the fact that the member is const .


Example:

#include <iostream>

struct Foo
{
    const int a = 0;
    int b;
    Foo() : b{42} {
        auto f = [this]() { std::cout << a << " " << b << std::endl; };
//                ^^^^ 
        f();
    }
};

int main() {
    Foo x;
}

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