簡體   English   中英

如果函數調用導致通過引用傳遞,為什么共享指針用於字符串?

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

在這個boost async 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM