c++ - g++ 不允许在 lambda 中通过引用广义捕获 const 对象?

标签 c++ lambda c++14

这被 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/

相关文章:

c++ - 用于线程的标准库版本 "Wait for Alert/Event"

c++ - GCC 5.3.1 C++ 在编译 Variadic 模板时停止

c++ - 使用 C++11 散列自己的字符串类型

c++ - std::vector<bool> resize() 的未定义行为

c++ - 为什么我不能将 [](auto&&...){} 转换为 std::function<void()>?

c++ - 尝试使用 Redispp 在类中设置全局 Redis 连接

c++ - 游戏对象工厂 : Fixing Memory Leaks

android - Android 设备的后退和主页按钮按下事件 (cocos2d-x 3)

java - 如何使用 java 8 stream api 更正编写代码?

c# - 使用 subselect 和 groupby 的 LINQ 仅获取列表中每个项目的最新版本