g ++不会允许通过引用在lambda中通用捕获const对象? [英] g++ won't allow generalized capture of const object by reference in lambda?

查看:702
本文介绍了g ++不会允许通过引用在lambda中通用捕获const对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这被g ++(4.9.3和5.2.0)拒绝,但被clang 3.5.0接受:

  int main(){
const int ci = 0;
auto lambda = [& cap = ci](){};
}

g ++给出错误:binding'const int'引用类型'int&'抛弃限定符。看来,g ++拒绝允许捕获非const引用,除非当然使用纯旧的C ++ 11捕获 [& ci] 。这似乎是一个非常奇怪的约束,也许是g ++中的错误?

解决方案

§5.1.2/ 11 go

的行为就像声明和显式地执行

捕获
auto init-capture ; 其声明区域是 的化合物语句 [...]


现在,清楚地声明

  auto& cap = ci; 

并捕获 cap 也就是说,

  int main(){
const int ci = 0;
auto& cap = ci;
auto lambda = [& cap](){};
}

与GCC编译。除了声明性区域和 cap 的生命周期,此代码段与您的代码段没有区别,因此GCC不正确。

此错误已经报告为 #66735 ,具有类似的示例:

  int x = 0; 
auto l = [& rx = static_cast< const int&>(x)] {};


This is rejected by g++ (4.9.3 and 5.2.0), but is accepted by clang 3.5.0:

int main() { 
    const int ci = 0;
    auto lambda = [ &cap = ci ]() { };
}

g++ gives error: binding ‘const int’ to reference of type ‘int&’ discards qualifiers. It appears that g++ refuses to allow non-const references to be captured, except of course using plain old C++11 capture [&ci]. That seems a very strange constraint, perhaps a bug in g++?

解决方案

Your code is valid. §5.1.2/11 goes

An init-capture behaves as if it declares and explicitly captures a variable of the form
"auto init-capture ;"
whose declarative region is the lambda-expression’s compound-statement […]

Now, clearly, declaring

auto &cap = ci;

and capturing cap is fine. That is,

int main() { 
    const int ci = 0;
    auto &cap = ci;
    auto lambda = [&cap]() { };
}

compiles with GCC. Apart from the declarative region and lifetime of cap, there is no difference between this snippet and yours, thus GCC is incorrect.
This bug has already been reported as #66735, with a similar example:

int x = 0;
auto l = [&rx = static_cast<const int&>(x)] {};

这篇关于g ++不会允许通过引用在lambda中通用捕获const对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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