【发布时间】:2021-09-29 21:11:53
【问题描述】:
auto 何时可以用作使用 lambda 函数初始化的变量的类型说明符?我尝试在以下程序中使用auto:
#include <iostream>
#include <functional>
class A
{
const std::function <void ()>* m_Lambda = nullptr;
public:
A(const std::function <void ()>& lambda): m_Lambda (&lambda) {}
void ExecuteLambda()
{
(*m_Lambda)();
}
};
void main()
{
int i1 = 1;
int i2 = 2;
const auto lambda = [&]()
{
std::cout << "i1 == " << i1 << std::endl;
std::cout << "i2 == " << i2 << std::endl;
};
A a(lambda);
a.ExecuteLambda();
}
我正在使用 Visual Studio Community 2019,当我开始执行 a.ExecuteLambda() 时,程序停止并出现以下异常:
Unhandled exception at 0x76D9B5B2 in lambda.exe:
Microsoft C ++ exception: std :: bad_function_call at memory location 0x00B5F434.
如果我将const auto lambda = [&]() 更改为const std::function <void ()> lambda = [&](),它会完美运行。为什么不允许使用auto?可以更改某些内容以允许使用它吗?
【问题讨论】:
标签: c++ exception lambda std-function