簡體   English   中英

Lambda 將引用復制到 lambda 引用 VS2017 編譯錯誤

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

在 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM