【问题标题】:Why is a shared pointer used for the string if the function call results in pass by reference?如果函数调用导致按引用传递,为什么要为字符串使用共享指针?
【发布时间】:2013-06-03 09:59:07
【问题描述】:

在这个 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 

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

【问题讨论】:

    标签: c++ boost shared-ptr boost-smart-ptr


    【解决方案1】:

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

    函数handle_send() 需要shared_ptrstring。由于调用是异步的,具有自动存储持续时间的string 对象可能已经超出范围并在handle_send() 执行时被销毁。因此,使用shared_ptr

    【讨论】:

      猜你喜欢
      • 2019-12-14
      • 2014-11-25
      • 2015-02-16
      • 2019-04-24
      • 2014-02-20
      • 2015-06-03
      • 2020-12-17
      • 2015-05-26
      • 1970-01-01
      相关资源
      最近更新 更多