mercredi 2 août 2017

Valid use case for delete this?

I'm using something pretty close to delete this, and wondering if this is a valid use case. I have a set of classes derived from ProcessingStage, and the framework using it has a unique_ptr<ProcessingStage> ps on which it calls ps->Process(input) in some loop reading the streaming input. Each derived class knows when it needs to switch to a different stage in its Process(), and holds a reference to the unique_ptr of the base used by the framework. So in Process() when such a condition is detected, I do ps.reset(new SomeOtherStage(init_params)). The external loop doesn't need to know anything about the change of processing type, it just keeps using the base pointer. I assume that the current derived object is destroyed and replaced by a new one at that point, so that if Process() returns immediately after doing this, there's no problem.

By the way, I'm not using shared_ptr since I see no benefit of reference counting here given the derived class will always only exist within the scope of the external base class pointer; I'm just storing a reference to that external unique_ptr passed in by reference from the constructor (I could alternately pass it into Process() each time to clarify that there is no ownership implied). Any gotcha to consider about this?

Aucun commentaire:

Enregistrer un commentaire