Suppose my application is using a library object Server which has a callback onConnected, which passes a reference to a Connection object when a new connection is established with a client; the Server retains ownership of the Connection. I would like to destroy the Connection when it is closed (whether locally or remotely), but I’m not sure how best to deal with notifying the application that is using the connection.
The obvious solution is to have some sort of onDisconnected callback and either delete it immediately, allowing the application to crash if it tries to continue using it, or pass it as shared_ptr and just let the object linger until the application cleans it up. Neither of these approaches feels particularly nice to me. The former just feels unsafe, and the latter muddies the concept of who owns the connection and makes leaks possible if the application ignores the callback.
Is there some idiomatic solution to this that I’m missing, or just a better way of doing it?
It’s unclear whether you’re writing the library component or the application (or both), but if you don’t own the object then it’s not up to you to decide when to destroy it.
But look at how connection handles usually work in OS networking libraries; the application’s connection handles don’t suddenly become invalid when the connection closes. The application is the owner of its handle on the connection and is responsible for correctly closing it. But ultimately the actual data structures for dealing with the connection are owned by the kernel, and can be discarded when the connection is no longer actually open. Then the application will get well defined errors when trying to use the shut down connection.