Search code examples
c++visual-c++boostboost-asioboost-bind

Can I use boost::bind to store an unrelated object?


Can I use boost::bind to make the resulting function object store an object which is not declared as argument to the bound target function? For example:

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));
}

ps. I'm mostly interested in an already existing syntax of doing this. I know I can make custom code to do it myself. I also know I can keep the timer alive manually, but I would like to avoid that.


Solution

  • Yes, you can do this by binding the extra parameters. I often did that with asio, e.g. in order to keep buffers or other state alive during the async operation.

    You can also access these extra arguments from the handler afterwards by extending the handler signature to utilize them:

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