1

In this example of using a boost asynchronous timer inside a class, the author added "this" pointer to the bind function inside m_timer.async_wait method.

That's strange because the handler is a public method (message(void)) that takes no argument, so why the hell using boost::bind and especially the pointer "this" ?

class handler
{
public:
  handler(boost::asio::io_service& io)
    : m_timer(io, boost::posix_time::seconds(1)),
      m_count(0)
  {
    m_timer.async_wait(boost::bind(&handler::message, this));
  }

  ~handler()
  {
    std::cout << "The last count : " << m_count << "\n";
  }

  void message()
  {
    if (m_count < 5)
    {
      std::cout << m_count << "\n";
      ++m_count;

      m_timer.expires_at(m_timer.expires_at() + boost::posix_time::seconds(1));
      m_timer.async_wait(boost::bind(&handler::message, this));
    }
  }

private:
  boost::asio::deadline_timer m_timer;
  int m_count;
};

int main()
{
  boost::asio::io_service io;
  handler h(io);
  io.run();

  return 0;
}
Aminos
  • 754
  • 1
  • 20
  • 40

1 Answers1

2

void handler::message() is a non-static member-function, as such it must be invoked on an object of type handler (or a derived type thereof).

This further means that we must say on which object this member-function is to be invoked when trying to pass it as a callback to some other function.

m_timer.async_wait(boost::bind(&handler::message,    this));
//                             ^- call this function ^- on this object

By passing this to boost::bind as you have shown, we express that we would like to invoke the member-function, who's address is &handler::message, on the current object (ie. this).


Note: The whole expression is equivalent telling m_timer.async_wait to call this->handler::message() (or this->message() for short).

Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196