如果函数调用导致引用传递,为什么要将共享指针用于字符串?
Why is a shared pointer used for the string if the function call results in pass by reference?
在这个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_ptr
到string
。由于调用是异步的,具有自动存储持续时间的string
对象可能在执行handle_send()
时已经脱离作用域并被销毁。因此,使用shared_ptr
.
相关文章:
- 如何从具有移动语义的类对象中生成共享指针
- 使用共享指针的函数调用,其对象应为 const
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 如何访问由共享指针保存的类方法?
- 从矢量或地图中删除共享指针
- 使用共享指针时,从共享指针本身释放内存的机制是什么
- 使用共享指针实现复制 c'tor?
- 共享指针继承,而不先显式强制转换
- 如何检查类中共享指针的有效性?
- std::排序在共享指针的向量上
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- 嵌套类、继承和C++中的共享指针
- 制作一对共享指针并推送一个向量
- 如何将共享指针用作函数参数
- 是否可以/希望创建不可复制的共享指针模拟(以启用weak_ptr跟踪/借用类型语义)?
- 尝试通过共享指针使用变量时读取访问冲突
- 如何将元素插入到标准::地图的共享指针中?
- 共享指针生存期
- 初始化可变数据结构中的共享指针向量
- 阻止在返回时复制共享指针