this is quite hard to explain but I'll try my best. So, I have a RenderComponent, EventManager and RenderSystem. In my RenderComponents constructor, I raise a renderComponentCreated event which the RenderSystem subscribes to. Using an event args object, I pass a RenderNode as data which contains the information the renderSystem needs to draw the thing (drawable, position and type).
So far so good. Now, when the renderComponent is deleted, I want the RenderNode to be removed from the RenderSystem automatically while still leaving the option to remove it manually e.g. as a reaction to some event. This could be done using a RenderComponentRemoveNodeEvent which again the RenderSystem subscribes to.
Now the 'problem'. From my understanding (and from what I want) the renderNode should be something uniquely owned by the RenderComponent (hence unique_ptr). However, this would require me to either copy (and implement a comparison operator for the renderNode --> to be able to find it when I want to remove it) or pass a reference / raw pointer to the renderNode. However, (If I'm correct) there is no way to know whether a reference still refers to a valid object which would mean that automatic removal could not be implemented.
My solution was to make the RenderNode (that is uniquely owned by the RenderComponent) shared and pass weak pointers to the event. The RenderSystem also now maintains a list of weak pointers that it checks for whether they are still pointing to a valid object and automatically removes them if not. So essentially what I would have wanted is creating a weak pointer from a unique one. However, the way it is now, someone could just create a shared pointer from the weak pointer and keep the RenderNode alive longer than it should. Since the managed object itself (RenderNode) contains references to other objects that will not exist longer than the RenderComponent this may cause serious issues.
My question now: can this be considered good design or have I missed something?
PS: Sorry if this explanation reads a bit clunky (English is not my native) and thanks for your help!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…