【问题标题】:Crash when std::function is constructed from lambda returned value in VS 2012从 VS 2012 中的 lambda 返回值构造 std::function 时崩溃
【发布时间】:2023-03-29 04:06:02
【问题描述】:

此 C++ 代码使用 VS 2012 成功编译,但在运行时崩溃:

#include <iostream>
#include <functional>

void f()
{
  std::cout << "f called" << std::endl;
}

int main()
{
  auto get_f= []()
    {
        bool b = true;
        return b ? f : f;
    };

  std::function<void()> filter(get_f()); // crash here!!!
  return 0;
}

如果我们把 get_f 改成这样:

auto get_f= []()
{
   return f;
};

然后程序运行而不会崩溃。

是这段代码的问题还是编译器/标准库的错误?

我尚未使用较新版本的 Visual Studio 进行测试。

【问题讨论】:

  • 您可能会在较新版本上获得更多运气。 &lt;functional&gt; 标头最近 IIRC 进行了重大改造。
  • VS 2013 update 4 就可以了。
  • VS 2015 也免费供个人使用:D

标签: c++ visual-studio c++11 visual-studio-2012 visual-c++


【解决方案1】:

在我看来,这是标准库(或可能是编译器)的问题。

使用 VS 2013,它可以毫无问题地编译和运行。如果我们添加代码来调用同样运行的filter

#include <iostream>
#include <functional>

void f()
{
  std::cout << "f called" << std::endl;
}

int main()
{
  auto get_f= []()
    {
        bool b = true;
        return b ? f : f;
    };

  std::function<void()> filter(get_f()); // crash here!!!
  filter();
  return 0;
}

输出:f called

【讨论】:

    猜你喜欢
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    相关资源
    最近更新 更多