Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost asio and the proliferation of shared_ptrs

I've recently started using boost. So far most things have been pretty straight forward. But one thing that is driving me nuts is the proliferation of shared_ptr throughout boost. Even in trivial examples, shared_ptr is used.

So my question is, if I am using boost for accepting tcp connections and then handling them. As long as I guarantee that the objects created on the heap (the boost::asio::ip::tcp::socket, and the class that will be called back for async methods) will not be deleted until I am done using tcp, then I don't need shared_ptr correct?

I've written a simple tcp server and client, not using shared ptr, it works. But I'd just like some outside confirmation that my assessment is correct.

Also, in your experience have you ever had a need to use shared_ptr to appease boost?

like image 396
anio Avatar asked Jan 21 '23 03:01

anio


1 Answers

Read the documentation for the io_service destructor

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.

in other words, it will be exponentially easier to use a shared_ptr instead of naked pointers.

like image 54
Sam Miller Avatar answered Jan 31 '23 09:01

Sam Miller