提升async_wait并在绑定中添加“this”

时间:2015-10-09 17:57:42

标签: c++ boost boost-asio

在这个在类中使用boost异步计时器的例子中,作者在m_timer.async_wait方法中添加了“this”指向bind函数的指针。

这很奇怪,因为处理程序是一个不带参数的公共方法(message(void)),为什么地狱使用boost :: bind,特别是指针“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 个答案:

答案 0 :(得分:2)

void handler::message()是一个非静态成员函数,因此必须在 handler 类型的对象(或其派生类型)上调用它。

这进一步意味着我们必须说明在尝试将其作为回调传递给其他函数时调用此成员函数的对象。

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

如您所示,将this传递给boost::bind,我们表示我们想在当前对象上调用成员函数,其地址为&handler::message(即。 this)。


注意:整个表达式相当于告诉m_timer.async_wait调用this->handler::message()(或简称为this->message())。