我的lambda参数是否真的影响我的本地人? [英] Are my lambda parameters really shadowing my locals?

查看:212
本文介绍了我的lambda参数是否真的影响我的本地人?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  void返回一个C代码,它接收一些数据并将其转发给传入的函数: foo(int * data,void(* fun)(int *)){
(* fun)(data);
};

以下工作没有警告:

  void bar(int * data){}; 

int main(){
int data = 0;
foo(& data,bar);
}

然而,如果我使用lambda代替:

  int main(){

int data = 0;
foo(& data,[](auto data){});
}

我收到以下警告:

 警告:'data'声明会影响前一个本地[-Wshadow] 
foo(& data,[](auto data){});
^
o.cpp:14:7:注意:影子声明在这里
int data = 0;

但我认为一个空的捕获组会在查找过程中排除第一个实例化。



这个警告合法吗?

为什么不是空的捕捉足以避免警告?

解决方案

lambda封闭范围中的名称也在lambda范围内。



被捕获的可能仍然可以使用,只要它们不是 odr-used 。只有 odr-used 变量必须被捕获。例子:

  #include > 

模板< typename T> void foo(const int *,T f){std :: cout<< f(5)< \\\
; }

int main()
{
const int data = 0;
foo(& data,[](int baz){
返回数据;
});

$ / code>

因为读取常量表达式不是 odr-use ,这段代码是正确的, data 引用 main 中的变量。



该程序输出 0 ,但如果将 int baz 更改为 int data ,它输出 5


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);
};

The following works without warning:

void bar(int* data){};

int main(){
  int data=0;
  foo(&data,bar);
}

However, if I use a lambda instead:

int main(){

  int data=0;
  foo(&data,[](auto data){});
}

I get the following warning:

warning: declaration of ‘data’ shadows a previous local [-Wshadow]
   foo(&data,[](auto data){});
                         ^
o.cpp:14:7: note: shadowed declaration is here
   int data=0;

But I thought an empty capture group would exclude the first instantiation during its look up.

Is this warning legitimate?
Why isn't the empty capture enough to avoid warnings?

解决方案

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 <iostream>

template<typename T> 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.

这篇关于我的lambda参数是否真的影响我的本地人?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆