I create a lambda function to run code in a different thread or simply to run it a bit later, but it can happen that an object kept by the lambda function is deleted in the mean time.
How can I detect that and not run the function in that case?
for instance
class A
{
public:
A(){}
virtual void test(){std::cout << m;}
int m;
};
int main()
{
A* a = new A();
std::function<void ()> function = [=]()->void
{
//if( pointer to 'a' still valid )
{
a->test();
}
};
delete a;
//or if( pointer to 'a' still valid )
function();
system("pause");
return 0;
}
or the detection could be done before executing the lambda function too.
An other idea is to have an object "Runnable" keep the lambda function and register it to the one that can be deleted. Then in the destructor I would notify the Runnable and prevent the execution.
Would that be a good way to do it ?