gpt4 book ai didi

c++ - std::visit 和 MSVC 调试器的堆栈损坏 "overloaded"结构

转载 作者:太空狗 更新时间:2023-10-29 23:10:50 25 4
gpt4 key购买 nike

我正在研究 cppreference.com page for std::visit 中的代码并使用以下代码在 Visual Studio 2017(15.9.6 和 15.9.7)调试版本(x86 和 x64,有或没有附加到进程的调试器)中遇到问题:

#include <iostream>

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...)->overloaded<Ts...>;

int main()
{
auto op = overloaded{
[](int x) { std::cout << "Got int: " << x << '\n'; },
[](const char* s) { std::cout << "Got cstring: " << s << '\n'; }
};

op(4);
op("Hello");
}

函数退出时,程序失败并显示消息“Run-Time Check Failure #2 - Stack around the variable 'op' was corrupted.”

发布版本不会抛出这个错误,当我在 g++ 和 clang++ 下编译它时,我没有遇到这个问题。

我还注意到按如下方式设置 op 可以解决问题:

auto l1 = [](int x) { std::cout << "Got int: " << x << '\n'; };
auto l2 = [](const char* s) { std::cout << "Got cstring: " << s << '\n'; };

auto op = overloaded{l1, l2};

第一个代码示例是否导致了未定义的行为和/或我遇到了编译器错误?

最佳答案

事实证明这段代码应该有效,我遇到了 Visual Studio bug .

关于c++ - std::visit 和 MSVC 调试器的堆栈损坏 "overloaded"结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54679134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com