如果函数调用导致引用传递,为什么要将共享指针用于字符串?

Why is a shared pointer used for the string if the function call results in pass by reference?

本文关键字:共享 指针 用于 字符串 为什么 函数调用 引用 如果      更新时间:2023-10-16

在这个boost异步udp服务器的例子中: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));
从http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/basic_datagram_socket/async_send_to/overload1.html

第一个参数的签名通过引用

传递
const ConstBufferSequence & buffers 

那么为什么要发送的消息使用共享指针?

这是因为字符串不仅作为第一个参数传递给async_send_to(),而且还用于作为第三个参数传递给async_send_to()bind()表达式。

函数handle_send()期望shared_ptrstring。由于调用是异步的,具有自动存储持续时间的string对象可能在执行handle_send()时已经脱离作用域并被销毁。因此,使用shared_ptr .