I find that if a lambda is a recursive function which is calling itself, then it can't be captured by another lambda as working in a closure in C++.
I have some codes like this:
#include <memory>
#include <functional>
#include <iostream>
class ClassA
{
public:
std::function<void()> FuncA;
void Call()
{
FuncA();
}
};
class ClassB
{
std::unique_ptr<ClassA> pA = std::make_unique<ClassA>();
public:
void Setup()
{
std::function<void(int)> FuncB = [&](int a)
{
std::cout << "a = " << a << std::endl;
if(a > 0)
FuncB(a-1);
};
pA->FuncA = [&]()
{
FuncB(10.0f);
};
}
void Run()
{
Setup();
pA->Call();
}
};
int main() {
ClassB B;
B.Run();
}
a exception will occur when running to calling FuncA, because FuncB in it will be a empty pointer.
My question is why can't I capture a recursive lambda function?
I'm using Visual Studio 2015
EDIT: If capture FuncB by copy in FuncA, then it works if FuncB is not recursive. like this:
class ClassB
{
std::unique_ptr<ClassA> pA = std::make_unique<ClassA>();
public:
void Setup()
{
std::function<void(int)> FuncB = [FuncB](int a)
{
std::cout << "a = " << a << std::endl;
if (a > 0)
FuncB(a - 1);
};
pA->FuncA = [FuncB]()
{
FuncB(10.0f);
};
}
void Run()
{
Setup();
pA->Call();
}
};
funcBno longer exists afterSetupfinished so yeah that's not going to end well.