I have an boost asio server application and I’m struggling with how to transmit created sockets (e.g. transmit accept socket to the protocol implementation classes that will read/write data down the road)
For example if I make them being transmitted by shared_ptr to different classes that read/write to them it works out. My server has an io_service.run() before exiting the main program and all async operations done on those sockets are performed in there.
EDIT I found out that the problem was not the way I was transmitting socket class. It is possible to keep ownership of these in a class and passing reference down the road. In my case one of the connection classes were being destroyed before async operation handler finished their work.
I think this question actually has nothing to do specifically with asio and could be genericized to “How should I transfer ownership of allocated objects?”.
And my answer would be: Use
std::unique_ptr(…for C++11)
If the receiver of the
unique_ptrwants to use a different ownership idiom (likeshared_ptr) it’s easy to release from theunique_ptrand turn it into ashared_ptr. The opposite isn’t true. This way, there is no time when your pointer is raw and could be leaked.