boost async_wait and adding “this” in a bind [duplicate]

假装没事ソ 提交于 2019-12-08 07:47:08

问题


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

回答1:


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).



来源:https://stackoverflow.com/questions/33044461/boost-async-wait-and-adding-this-in-a-bind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!