Accessing lambda capture initialized variable outside the lambda in C++

后端 未结 2 601
青春惊慌失措
青春惊慌失措 2021-01-18 04:34

In C++14/17, how do you access a lambda capture initialized variable outside the scope of the lambda?

Source:

#include 

using namespac         


        
2条回答
  •  灰色年华
    2021-01-18 05:03

    Just for completeness, depending on the compiler it is technically possible to access the internal members of the lambda, and modify them. Although this is basically taking advantage of an implementation detail, and should never be done. But it does provide some insight into the lambda implementation.

    Here it is in GCC 6.3

    #include 
    
    using namespace std;
    
    template
    struct lambda_member : Lambda
    {
    
        Lambda& f_;
        lambda_member(Lambda& f) : Lambda(f),
            f_(f)
        {}
    
        auto& get_value1()
        {
            return f_.__value1;
        }
    
    };
    
    
    int main(){
        auto test = [value1 =0]() mutable {value1+=1; return value1;};
    
        lambda_member lm{test};
    
        std::cout << test() << std::endl;
        std::cout << lm.get_value1() << std::endl;
        lm.get_value1() = 22;
        std::cout << test() << std::endl;
    
    }
    

    Demo

提交回复
热议问题