在内部执行时重新分配std :: function对象 [英] Re-assigning an std::function object while inside its execution

查看:91
本文介绍了在内部执行时重新分配std :: function对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个std :: function对象,用作某个事件的回调。我为此对象分配了一个lambda,在其中,我将该对象分配给了不同的lambda执行中。执行此操作时会出现段错误。这不是我可以做的吗?如果是这样,为什么?我将如何实现这一目标?

I have an std::function object I'm using as a callback to some event. I'm assigning a lambda to this object, within which, I assign the object to a different lambda mid execution. I get a segfault when I do this. Is this not something I'm allowed to do? If so, why? And how would I go about achieving this?

声明:

std::function<void(Data *)> doCallback;

致电:

//
// This gets called after a sendDataRequest call returns with data
//
void onIncomingData(Data *data)
{
    if ( doCallback )
    {
        doCallback(data);
    }
}

分配:

doCallback =
    [=](Data *data)
    {
        //
        // Change the callback within itself because we want to do 
        // something else after getting one request  
        //
        doCallback =
            [=](Data *data2)
            {
                ... do some work ...
            };
        sendDataRequest();
    };
sendDataRequest();


推荐答案

std :: function :: operator(),该函数使用其内部状态对象。实际上,某些实现在调用之后使用它。

The standard does not specify when in the operation of std::function::operator() that the function uses its internal state object. In practice, some implementations use it after the call.

所以您所做的是不确定的行为,尤其是崩溃。

So what you did was undefined behaviour, and in particular it crashes.

struct bob {
  std::function<void()> task;
  std::function<void()> next_task;
  void operator()(){
    next_task=task;
    task();
    task=std::move(next_task);
  }
}

现在是否要更改下一次的操作调用 bob()中的 bob ,只需设置 next_task

now if you want to change what happens when you next invoke bob within bob(), simply set next_task.

这篇关于在内部执行时重新分配std :: function对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆