我最近开始使用 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/