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

后端 未结 2 584
暗喜
暗喜 2020-12-28 13:12

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:



        
相关标签:
2条回答
  • 2020-12-28 13:30

    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;
    }
    
    0 讨论(0)
  • 2020-12-28 13:32

    Only objects with automatic storage duration can be captured by a lambda in C++11 (i.e. 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.

    0 讨论(0)
提交回复
热议问题