capture by value class members

后端 未结 3 1758
温柔的废话
温柔的废话 2021-02-02 08:49

Is there a way, when writing a lambda function within a member function, to capture fields of the enclosing class by value? The default catch-all = doesn\'t work be

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-02 09:01

    Yes, simply write the [=] construct. For instance:

    class MyClass {
        int a;
        void foo() {
            auto my_lambda = [a_by_val=a] {
                // do something with a_by_val
            }
    
            my_lambda();
        }
    }
    

提交回复
热议问题