In this boost async udp server example: http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/tutorial/tutdaytime6/src.html
boost::shared_ptr<std::string> message(
new std::string(make_daytime_string()));
socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
boost::bind(&udp_server::handle_send, this, message,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
the signature of 1st argument is pass by reference
const ConstBufferSequence & buffers
then why is a shared pointer used for the message to be send?
That is because the string is not just passed as the first argument to async_send_to()
, but it is also used in the bind()
expression that is being passed to async_send_to()
as the third argument.
Function handle_send()
expects a shared_ptr
to a string
. Since the call is asynchronous, a string
object with automatic storage duration may have fallen out of scope and get destroyed by the time handle_send()
gets executed. Hence, the use of a shared_ptr
.