c++ - boost async_wait 并在绑定(bind)中添加 "this"

标签 c++ boost boost-asio

<分区>

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

这很奇怪,因为处理程序是一个不带参数的公共(public)方法 (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() 是一个非静态成员函数,因此它必须在 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()

关于c++ - boost async_wait 并在绑定(bind)中添加 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33044461/

相关文章:

c++ - 为 gettext boost 语言环境 "Conversion failed"

c++ - 如何混合使用 boost::bind 和 C 函数指针来实现回调

c++ - 无法实现 boost::asio::ssl::stream<boost::asio::ip::tcp::socket> 重新连接到服务器

c++ - 分析 concurrency::task() API 以及我们为什么需要这个?

c++ - 按执行顺序创建pthread

c++ - 在构造函数定义中调用函数后收到 Segmentation Fault 11 错误?

c++ - 使用 C++ Boost 间隔容器库 (ICL) 时如何移动间隔?

c++ - 如何从 boost::asio::ssl::stream<boost::asio::ip::tcp::socket> 获取 native 套接字文件描述符?

c++ - Boost Asio 与一次性对象共享相同的 io_service

c++ - main() 总是返回 int?