I've noticed 3 main options to call handler for async operations in Boost.Asio:
class MyClass {
public:
void doReadFromSocket(); //implementation options provided below.
private:
void handleRead(const boost::system::error_code& ec,
std::size_t bytesTransferred) {
// ... handle async_read result.
}
boost::asio::streambuf m_buffer;
boost::asio::ip::tcp::socket m_socket;
}
Option 1 - use lambda function:
void MyClass::doReadFromSocket() {
boost::asio::async_read(m_socket, m_bufferIn,
boost::asio::transfer_at_least(1),
[this](const boost::system::error_code& ec,
std::size_t bytesTransferred) {
// ...
}
}
Option 2 - use direct member function call: UPD. The option is not correct, as pointed out in the comments.
void MyClass::doReadFromSocket() {
boost::asio::async_read(m_socket, m_bufferIn,
boost::asio::transfer_at_least(1),
handleRead);
}
Option 3 - use boost::bind to call member function that handles the read:
void MyClass::doReadFromSocket() {
boost::asio::async_read(m_socket, m_bufferIn,
boost::asio::transfer_at_least(1),
boost::bind(&MyClass::handleRead, this, _1, _2));
}
}
The main questions are:
- Are there any differences in those ways to handle the read operation, especially in terms of performance?
- Why do we need
boost::bind
to handle the read? Why not use a direct member function call? A lot of examples in the boost library useboost::bind
to handle async operations. Also, this option seems the least convenient from my perspective