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

后端 未结 2 595
暗喜
暗喜 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 
    
    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;
    }
    

提交回复
热议问题