Lambda复制对Lambda参考VS2017的引用的编译错误

时间:2019-03-26 15:23:26

标签: c++ lambda

在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更有趣,可以解决编译器错误。

0 个答案:

没有答案