how to delete two objects that are circularly linked

Started by
10 comments, last by JohnnyCode 10 years, 3 months ago


Under what circumstances would the Node ever want to destroy the Entity?

Thanks for the reply. I haven't seriously thought about the use case, I just thought it would be convenient. But yes, I probably won't needs this kind of feature.

Advertisement


use a shared_ptr in Entity. This gives a many-to-one relationship

thanks for the reply. using shared_ptr might be a good option for me.

(1) Node is basically a hierarchical representation of transformation, and Entity is object in the game scene. Every Entity must have a node, each node can have several child nodes.

What I want to do is

(2) deleting either of entity or node will delete both of them, and also

(3) deleting a node will somehow notify its parent.

If this is a design requirement, and you can assure that entity-node is one-to-one relation, meaning an entity has exclusive node, and a node has exclusive entity, then, you could elegantly solve all requirements by inheritance. You can implement inheritance effect in pointer logic and in not deriving languages, just study what inheritance exactly is. With inheritance, if you delete a node, it will properly destroy entity, then node, and free memory that was allocated on the instance containing the node, the same if you delete entity.

CEntity* e= new CEntity(const node);

CEntity* e2= new CEntity(const node2);

Cnode* nd=new CNode();

delete (CNode*) e; // frees entity and node, calling destructors in correct order

delete nd; // frees only node, since mem manager is aware of how it was allocated


If this is a design requirement, and you can assure that entity-node is one-to-one relation, meaning an entity has exclusive node, and a node has exclusive entity

That's not what is required, however. The requirement is each entity has exactly one node, and each node may have several entities.

You can implement inheritance effect in pointer logic and in not deriving languages, just study what inheritance exactly is.

[...]
CEntity* e= new CEntity(const node);
[...]
delete (CNode*) e;

If there is no real inheritance, that's deleting the wrong type of object, so it's UB. It won't magically do what is intended either.

Although in this example, at least it might not crash, since the destructors are likely trivial. So calling the wrong destructor probably won't do much evil (and the standard allocator knows the size of the allocated block of raw memory). But it's still wrong, and a source of impossible to debug errors in the future (and woe if you overload the allocator, e.g. using C++1y sized operator delete some day in the future).

This topic is closed to new replies.

Advertisement