这被 g++(4.9.3 和 5.2.0)拒绝,但被 clang 3.5.0 接受:
int main() {
const int ci = 0;
auto lambda = [ &cap = ci ]() { };
}
g++ 给出错误:将“const int”绑定(bind)到“int&”类型的引用会丢弃限定符
。看起来 g++ 拒绝允许捕获非常量引用,当然除了使用普通的旧 C++11 捕获 [&ci]
。这似乎是一个非常奇怪的约束,也许是 g++ 中的错误?
最佳答案
您的代码有效。 §5.1.2/11 去
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 […]
现在,清楚地声明
auto &cap = ci;
并捕获 cap
没问题。也就是说,
int main() {
const int ci = 0;
auto &cap = ci;
auto lambda = [&cap]() { };
}
compiles with GCC .除了 cap
的声明区域和生命周期之外,此代码段与您的代码段没有区别,因此 GCC 不正确。
此错误已报告为 #66735 ,用一个类似的例子:
int x = 0;
auto l = [&rx = static_cast<const int&>(x)] {};
关于c++ - g++ 不允许在 lambda 中通过引用广义捕获 const 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36791825/