Are my lambda parameters really shadowing my locals?

前端 未结 2 1363
無奈伤痛
無奈伤痛 2021-01-18 01:45

I\'m dealing with some C code that takes some data, and forwards it to the function passed in:

void foo(int* data, void (*fun)(int*)){
  (*fun)(data);
};
<         


        
2条回答
  •  抹茶落季
    2021-01-18 02:46

    Names from the enclosing scope of the lambda are also in the scope of the lambda.

    Names that are not captured may still be used, so long as they are not odr-used. Only odr-used variables must be captured. Example:

    #include 
    
    template void foo(const int *, T f) { std::cout << f(5) << '\n'; }
    
    int main()
    {
        const int data=0;
        foo(&data,[](int baz){
            return data;
        });
    }
    

    Because reading a constant expression is not odr-use, this code is correct and data refers to the variable in main.

    This program outputs 0, but if you change int baz to int data, it outputs 5.

提交回复
热议问题