gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:54:38 25 4
gpt4 key购买 nike

在这个 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(),而且还在被传递的 bind() 表达式中使用async_send_to() 作为第三个​​ 参数。

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

关于c++ - 如果函数调用导致按引用传递,为什么要为字符串使用共享指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16894161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com