When can auto
be used as the type specifier of a variable initialized with a lambda function? I'm try to use auto
in the following program:
#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();
}
I'm using Visual Studio Community 2019 and when I start executing a.ExecuteLambda()
, the program stops with the following exception:
Unhandled exception at 0x76D9B5B2 in lambda.exe:
Microsoft C ++ exception: std :: bad_function_call at memory location 0x00B5F434.
If I change the line const auto lambda = [&]()
to const std::function <void ()> lambda = [&]()
, it works perfectly. Why is it not allowed to use auto
? Can something be changed to allow it to be used?