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

标签 c++ visual-c++ boost boost-asio boost-bind

我可以使用 boost::bind 使生成的函数对象存储一个未声明为绑定(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));
}

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

最佳答案

是的,您可以通过绑定(bind)额外的参数来做到这一点。我经常用 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));

关于c++ - 我可以使用 boost::bind 来存储不相关的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41934804/

相关文章:

c++ - 内存泄漏了吗?

c - 优化时,在现代编译器中使用 `register` 关键字是否无用?

python - 用Python Boost包装C++ operator()

c++ - boost::object_pool是否同步?

c++ - boost::bind 与空函数指针

c++ - 在模板类之外定义方法

c++ - 调整不可迭代容器以通过自定义模板化迭代器进行迭代

c++ - 鼠标事件选择器openscenegraph

linux - 使用 gcc 查找要在项目中链接的 .o 文件顺序的任何工具

java - JNI NewByteArray 内存泄漏