1

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 ?

4

2 回答 2

2

您无法测试指针指向的对象是否已被删除。

如果它已被删除,您的 test() 将只有未定义的行为。

于 2013-03-05T21:46:00.497 回答
0

这是一个解决方案:

std::shared_ptr<A> a(new A());
std::weak_ptr<A> weak_a(a);
std::function<void ()> function = [weak_a]()->void
{
    if( std::shared_ptr<A> a = weak_a.lock() )
    {
        // to get the A* from a, do a.get()
        // operator-> and *a work however:
        a->test();
    }
};
a.reset(); // instead of delete

的使用weak_ptr是可选的——如果您改为将其shared_ptr复制到 lambda,则 lambda 的生命周期a将延长 lambda 的生命周期。

这确实要求a在 lambda 之外使用的代码是shared_ptr兼容的。

于 2013-03-06T15:00:32.067 回答