c++ - Lambda 复制对 lambda 引用的引用 VS2017 编译错误
问题描述
在 Visual Studio 2017 中编译以下代码:
#include "pch.h"
#include <iostream>
int main()
{
int test = 5;
auto cb1 = [test]()
{
auto cb2 = [&]()
{
auto cb3 = [test]()
{
std::cout << test;
};
cb3();
};
cb2();
};
cb1();
}
给出编译器错误
test.cpp(17): error C2440: '<function-style-cast>': cannot convert from 'const int' to 'main::<lambda_80fd0d4feae1377a5d8b8955e10105ab>::()::<lambda_38fc83ae6a7bd6540ebe1721869db4f1>'
test.cpp(17): note: No constructor could take the source type, or constructor overload resolution was ambiguous
test.cpp(18): error C3536: 'cb2': cannot be used before it is initialized
test.cpp(18): error C2064: term does not evaluate to a function taking 0 arguments
有人知道为什么 Visual Studio 会出现此错误吗?(在clang上似乎可以编译)您可以通过替换为什么可以修复错误来编译auto cb2 = [&]()
它auto cb2 = [&test]()
?
更有趣的添加std::cout << test;
或修复编译器错误const int &ref = test;
的主体。cb2
解决方案
这只是旧版 Visual Studio 编译器中的一个错误。可以通过实验看到该错误在 MSVC v16.10 之前一直存在,并且在 MSVC v16.11 中已修复。幸运的是,包括 Visual Studio 2019 在内的现代编译器接受您的程序。演示:https ://gcc.godbolt.org/z/rYG7Ma8n9
推荐阅读
- javascript - 根据外部ID在javascript中对数组进行排序
- rest - REST:哪个 HTTP 状态用于拒绝当前资源状态的方法
- dafny - 在 Dafny 中创建范围为 n 的数组的最佳方法?
- r - 带有计数的堆叠条形图中 geom_text 的百分比
- datatables - 同一页面上的数据表
- qt - QSqlTableModel: Where can I get whether a row is marked as removed
- r - 重命名分类级别以减少级别数
- ansible - Ansible Missing sudo password
- php - Laravel Models 一对多关系未建立
- javascript - 单击网站中的底部计数器:我想要一种方法使计数器从重新加载页面后到达的位置完成(继续)