Sam Millerβs shared_ptr response works because using shared_ptr holds a TimeBomb for the duration of a BomberMan. This may be good for you, or it may not be.
A suggestion for a more complete solution would be to get TimeBomb instances from the factory, which you then release before you finish, instead of adding and removing them explicitly (holding them as standard pointers, not shared_ptrs, since you don't own them even if you control the life cycle). factory can keep them hanging until they are undone, then delete them for you. Keep the Sam (Miller) Stop () function as is.
To implement this, take the factory out of the interface along the lines
class ITimeBombObserver { public: virtual void AllOperationsComplete(TimeBomb& TmBmb)=0; };
Pass your factory to each TimeBomb as an ITimeBombObserver when building and cancel the TimeBomb function with this function. factory can clean up the βusedβ TimeBombs every time it is created or released, or using a scheduled cleanup or some other method, depending on what is most suitable for your application.
Using this method, your BomberMan does not even need to explicitly allocate a TimeBomb in defuseBomb (), if it does not want it, the stop () call can be automatically released (although in this case you should still indicate the pointer as it is actually unusable at the moment). Whether this is a good idea or not depends on your real problem, so I will leave it to you to decide.
Knucklesthedog
source share