<分区>
在这个类中使用 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;
}