简体   繁体   English

Lambda 将引用复制到 lambda 引用 VS2017 编译错误

[英]Lambda copying a reference to a lambda reference VS2017 compile error

Compiling the following code in Visual Studio 2017:在 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();
}

Gives the compiler error给出编译器错误

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

Does anybody know why Visual Studio gives this error?有人知道为什么 Visual Studio 会出现此错误吗? (it seem to compile ok on clang) You can get it to compile by replacing auto cb2 = [&]() with auto cb2 = [&test]() why does that fix the errors? (它似乎在 clang 上编译正常)您可以通过将auto cb2 = [&]()替换为auto cb2 = [&test]()来编译它为什么会修复错误?

Even more interesting adding std::cout << test;更有趣的是添加std::cout << test; or const int &ref = test;const int &ref = test; to the body of cb2 fixes the compiler error. cb2的主体修复了编译器错误。

This is just a bug in older Visual Studio compilers.这只是旧版 Visual Studio 编译器中的一个错误。 One can see experimentally that the error was present till MSVC v16.10, and it was fixed in MSVC v16.11.可以通过实验看到该错误一直存在到 MSVC v16.10,并且在 MSVC v16.11 中已修复。 Fortunately, modern compilers including Visual Studio 2019 accept your program.幸运的是,包括 Visual Studio 2019 在内的现代编译器接受您的程序。 Demo: https://gcc.godbolt.org/z/rYG7Ma8n9演示: https : //gcc.godbolt.org/z/rYG7Ma8n9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM