Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

c++ - g++ won't allow generalized capture of const object by reference in lambda?

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++?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...