C++ 如果函数调用导致按引用传递,为什么字符串使用共享指针?
在此boost异步udp服务器示例中:C++ 如果函数调用导致按引用传递,为什么字符串使用共享指针?,c++,boost,shared-ptr,boost-smart-ptr,C++,Boost,Shared Ptr,Boost Smart Ptr,在此boost异步udp服务器示例中: 那么,为什么要将共享指针用于要发送的消息?这是因为该字符串不仅作为第一个参数传递给async\u send\u to(),而且还作为第三个参数传递给async\u send\u to()的bind()表达式 函数handle\u send()需要共享的\u ptr到字符串。由于调用是异步的,因此具有自动存储持续时间的字符串对象可能已超出范围,并在执行handle\u send()时被销毁。因此,使用共享\u ptr boost::shared_ptr
那么,为什么要将共享指针用于要发送的消息?这是因为该字符串不仅作为第一个参数传递给
async\u send\u to()
,而且还作为第三个参数传递给async\u send\u to()
的bind()
表达式
函数handle\u send()
需要共享的\u ptr
到字符串。由于调用是异步的,因此具有自动存储持续时间的字符串
对象可能已超出范围,并在执行handle\u send()
时被销毁。因此,使用共享\u ptr
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));
const ConstBufferSequence & buffers