c++ - boost asio 和 shared_ptr 的扩散

标签 c++ boost boost-asio

我最近开始使用 boost。到目前为止,大多数事情都非常简单。但是让我发疯的一件事是 shared_ptr 在整个 boost 过程中的扩散。即使在简单的示例中,也会使用 shared_ptr。

所以我的问题是,如果我使用 boost 来接受 tcp 连接然后处理它们。只要我保证在堆上创建的对象(boost::asio::ip::tcp::socket,以及将为异步方法回调的类)在我完成使用 tcp 之前不会被删除, 那么我不需要 shared_ptr 对吗?

我写了一个简单的 tcp 服务器和客户端,没有使用共享 ptr,它可以工作。但我只是想要一些外部确认,以证明我的评估是正确的。

此外,根据您的经验,您是否曾经需要使用 shared_ptr 来安抚 boost?

最佳答案

阅读documentation对于 io_service 析构函数

The destruction sequence described above permits programs to simplify their resource management by using shared_ptr<>. Where an object's lifetime is tied to the lifetime of a connection (or some other sequence of asynchronous operations), a shared_ptr to the object would be bound into the handlers for all asynchronous operations associated with it. This works as follows:

When a single connection ends, all associated asynchronous operations complete. The corresponding handler objects are destroyed, and all shared_ptr references to the objects are destroyed.

To shut down the whole program, the io_service function stop() is called to terminate any run() calls as soon as possible. The io_service destructor defined above destroys all handlers, causing all shared_ptr references to all connection objects to be destroyed.

换句话说,使用 shared_ptr 比使用裸指针要容易得多。

关于c++ - boost asio 和 shared_ptr 的扩散,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4099202/

相关文章:

c++ - 使用硬盘进行快速访问取代 RAM

c++ - C++ 中的二维 vector 数组

python - 使用宏从 __VA_ARGS__ 生成参数列表

c++ - boost::asio -- asio_handler_deallocate 在 io_service::~io_service() 中调用,在 io_service::stop() 之后

c++ - read_some() 工作但很慢, read() 没有

C++ Boost::Asio 我得到了 remote.Endpoint().address,现在如何解析主机名?

c++ - 类型、整型常量和模板模板参数的可变参数模板

c++ - 播放流声音OpenAL

c++ - 我可以从 boost::multi_array<T, 2> 得到 T**(c 风格的二维数组) 吗?

c++ - 在 Boost.Asio 请求期间检测中止的连接