Are my lambda parameters really shadowing my locals?

前端 未结 2 1398
無奈伤痛
無奈伤痛 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:28

    In reference to MISRA C++ 2008: An identifier declared in an inner scope should never have the same name as an identifier declared in the outer scope.

    In your example int data is declared in the outer scope but goes to the inner scope of your lambda via reference. The problem is that you also have a parameter in the parameter list of your lambda called data(inner scope). This leads to a hiding of the data variable from the outer scope within the lambda.

    By the way. Also your first example with function pointer should be rewritten because there is also a conflict with naming’s of identifiers in inner and outer scope. In this case it is not really bad cause effective there is only one data variable in use within the inner score. However, when parameter list variables and variables from the outer scope which calls the function have the same name this could lead to programmers confusion and should be also avoid.

提交回复
热议问题