I am for learning purposes writing a UDP client/server protocol in c++, where the communication from the server component of my application to the rest of the application is achieved using handlers.
For example, I might register an Authorization component against the value 1, and an TextMessage component against value 2. The client then first sends a message or two to the Authorization component to login and then starts sending text messages to the TextMessage handler.
This is what I have now:
class NetworkHandler {
virtual void handleMessage(const endpoint & endpoint, const buffer & message) = 0;
};
Any class that wish to register as a component simply subclass NetworkHandler and call
udpServer.addHandler(handler);
However, I'm having a few issues with deciding how I should pass the handlers, being a newbie and all.
Should I pass the handler by reference? This is easy and convenient, but the question of ownership comes into play - the calling function should probably not have to worry about keeping a reference around for no reason.
Should I copy the handler? This is also easy and convenient, but here there is a question of whether or not my handler is copyable or whether or not I need to keep a reference to my handler from outside the class.
What I am wondering is, what is the common best practice for this kind of situation? Sorry for wall of text.
When in doubt, share with a
shared_ptr
. That's self-documenting and almost always works, at the expense of some pointer indirection and one/two memory allocations.