我可以使用 boost::bind 来存储不相关的对象吗?



我可以使用boost::bind 使生成的函数对象存储未声明为绑定目标函数参数的对象吗?例如:

void Connect(const error_code& errorCode)
{
    ...
}
// Invokes Connect after 5 seconds.
void DelayedConnect()
{
    boost::shared_ptr<boost::asio::deadline_timer> timer =
        boost::make_shared<boost::asio::deadline_timer>(ioServiceFromSomewhere);
    timer->expires_from_now(
        boost::posix_time::seconds(5));
    // Here I would like to pass the smart pointer 'timer' to the 'bind function object'
    // so that the deadline_timer is kept alive, even if it is not an actual argument
    // to 'Connect'. Is this possible with the bind syntax or similar?
    timer->async_wait(
        boost::bind(&Connect, boost::asio::placeholders::error));
}

附言。我最感兴趣的是已经存在的语法。我知道我可以自己制作自定义代码来做。我也知道我可以手动保持计时器的活动,但我想避免这种情况。

是的,您可以通过绑定额外的参数来执行此操作。我经常使用 asio 这样做,例如,为了在异步操作期间保持缓冲区或其他状态处于活动状态。

之后,您还可以通过扩展处理程序签名来利用它们,从而从处理程序访问这些额外的参数:

void Connect(const error_code& errorCode, boost::shared_ptr<asio::deadline_timer> timer)
{
}
timer.async_wait(
    boost::bind(&Connect, boost::asio::placeholders::error, timer));

是的,您可以简单地绑定"太多"参数,它们不会传递给底层处理程序。请参阅为什么从绑定返回的对象会忽略额外的参数?

这没关系,除非您需要从 Connect 中"与计时器对象"对话"。

附言。另外,不要忘记在计时器被破坏时期望计时器完成operation_abandoned

最新更新