The MessageManager class is a wrapper around a c library with all the fun that brings along. The class retrieves all Messages available in the system. Since the class loads a lot of resources it is only used once in the software instance (in one thread). This class has an concept of ownership where the MessageManager needs to release resources via the ReturnCollection method. This means the user of the class first uses GetCollection to get a collection of messages, process the messages and then call ReturnCollection.
int GetCollection(DataCollection<Message>& collection);
int ReturnCollection(DataCollection<Message>& collection);
The usage of the ReturnCollection() method is a cumbersome and potentially error prone approach which I would like to solve in a generic way. One approach that I thought about was using an Iterator class where the Iterator's destructor would call the ReturnCollection. How would I implement such a feature? Could I pass a method pointer containing the address of the ReturnCollection method to the iterator class and then enabling the Iterator destructor to call ReturnCollection() method via the method pointer? Is this possible and a good approach?
this iterator stores the iterator of the underlying sequence and a shared_ptr to its container. Now, in order to achieve the wanted effect you simply have to replace the default deleter with a call to ReturnCollection, and that's it.