In the ASIO HTTP Server 3 example there is code like this:
void server::start_accept()
{
new_connection_.reset(new connection(io_service_, request_handler_));
acceptor_.async_accept(new_connection_->socket(),
boost::bind(&server::handle_accept, this,
boost::asio::placeholders::error));
}
void server::handle_accept(const boost::system::error_code& e)
{
if (!e)
{
new_connection_->start();
}
start_accept();
}
Essentially, new_connection_
is a member of the server
class and is used to pass a connection from start_accept
to handle_accept
. Now, I'm curious as to why new_connection_
is implemented as a member variable.
Wouldn't it also work to pass the connection using bind
instead of a member variable? Like this:
void server::start_accept()
{
std::shared_ptr<connection> new_connection(new connection(io_service_, request_handler_));
acceptor_.async_accept(new_connection_->socket(),
boost::bind(&server::handle_accept, this,
boost::asio::placeholders::error),
new_connection);
}
void server::handle_accept(boost::system::error_code const& error, std::shared_ptr<connection> new_connection)
{
if (!error) {
new_connection->start();
}
start_accept();
}
If so, why does the example use member variables? Is it to avoid the copying involved?
(note: I'm not comfortable with ASIO yet and so there may be a fundamental misconception here)