First off: I searched half the web to find an answer with this as a solution that came closest. It is, however, too heavyweight for me though so I am looking a little less complex.
Well then, some context: I am building a system which should be able to process incoming messages from a queue and then store the outcome of these messages in another queue. I would like to store these responses in a generic class because I am storing it in a multimap.
The response class currently is defined as follows
class COutboundMsg
{
public:
enum eTypeHint {
thNone,
thSomeType,
thLast
};
eTypeHint m_TypeHint;
void* m_OutboundData;
COutboundMsg(COutboundMsg::eTypeHint TypeHint, void* data);
};
COutboundMsg::COutboundMsg(COutboundMsg::eTypeHint TypeHint, void* data) :
m_TypeHint(TypeHint),
m_OutboundData(data)
{
}
Now, the current way of working would involve a user to do something like this:
CSomeType* data = new CSomeType();
COutboundMsg(COutboundMsg::thSomeType , (void*) data);
It would be up to the user at the other end to cast the void* back to CSomeType* (using the type hint) and delete it.
It don’t like it.
I’d rather have the m_OutboundData contained in an auto_ptr or something and make sure that it deletes itself when done.
Any ideas? Maybe a different approach altogether
Normally polymorphism is used for a system like this; any item that can be put in the Outbound queue derives from
QueueItemand the queue containsQueueItem*or a smart pointer to aQueueItem.Since the items all derive from a common base, you can safely delete the
QueueItem*or allow a smart pointer to handle it. This approach also allows you to usedynamic_castto make sure that the pointer is, in fact, pointing to an object of the type you think it is.If this approach is possible, be sure to make the
QueueItemdestructor virtual, otherwise the derived class’s destructor won’t be called.