提升async_wait并在绑定中添加"this"



在这个类中使用boost异步计时器的例子中,作者将"this"指针添加到m_timer内部的bind函数中。async_wait方法。

这很奇怪,因为处理程序是一个不接受参数的公共方法(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;
}

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

这进一步意味着,当试图将成员函数作为回调函数传递给其他函数时,必须说明在哪个对象上调用该成员函数。

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())。

最新更新