Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如果函数调用导致按引用传递,为什么字符串使用共享指针?_C++_Boost_Shared Ptr_Boost Smart Ptr - Fatal编程技术网

C++ 如果函数调用导致按引用传递,为什么字符串使用共享指针?

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

在此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<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