【问题标题】:boost async_wait and adding "this" in a bind [duplicate]提升 async_wait 并在绑定中添加“this”[重复]
【发布时间】:2016-01-07 18:25:59
【问题描述】:

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

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

【问题讨论】:

    标签: c++ boost boost-asio


    【解决方案1】:

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

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

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

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


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2015-08-10
      • 2023-03-03
      • 2017-01-07
      • 2016-05-16
      • 2013-12-18
      • 2021-01-07
      相关资源
      最近更新 更多