FatalCatharsis
FatalCatharsis

Reputation: 3567

How to "invalidate" an object like an stl iterator

Vague title, but it's a bit hard to explain what i need in 100 some characters. I have a map of maps that each contain a different type of derived objects. looks like this:

/* will use smart pointers in the final product, just using plain 
   pointers to simplify the example.*/

// The long is a type id and the string is a unique identifier
std::map<long, std::map<std::string, Node *> > m_NodeList;

Each of those Nodes contain one or more components depending on their specific type. These components are located in a different map in a map. Looks like this.

std::map<long, std::map<std::string, Component *> > m_ComponentList;

an example of this interaction is like this:

class Mesh :
    public Component
{
    // some graphics api stuff
};

class Vector3 :
    public Component
{
public:
    float x, y ,z;
};

class Graphics :
    public Node
{
public:
    Node(Vector3 & vec, Mesh & model) :
        m_Pos(vec),
        m_Model(model)
        {}

    Vector3 & m_Pos;
    Mesh & m_Model;
};

I've got a lot of the type magic worked out because I've done similar things before, but now i'm running into an issue of dependence. I would like for Component and Nodes to be able to be removed from the system at any given time. However, the Nodes always depend on the existence of the components. The logic comes out like this, If a node is removed, no change, if a component is removed, i also need to remove all Nodes which are dependent upon it. Let's say both of these maps exist within an object call Mediator. How would you guys keep a list of the dependencies so that the mediator would know to also destroy certain nodes? Also, if you would organize this scheme differently, i would like to hear it as well. Thanks in advance!

edit: also if you can think of a more relevant title to this, thank you -_-

Upvotes: 1

Views: 272

Answers (1)

Juraj Blaho
Juraj Blaho

Reputation: 13451

Component will need to point to all dependent nodes and remove them when destroying itself. Component needs to be notified when a dependent node is created or destroyed so that the component can update list of all dependent nodes.

Using Boost.Intrusive list with auto unlink for the list of dependent nodes may be beneficial, because when a node is destroyed, it is removed automatically from the list.

Storing nodes in Boost.Intrusive set with auto unlink instead of in std::map may help too.

Note that to remove a node from intrusive container, you don't need a pointer to the container itself. You just delete the node and it gets removed automatically.

Upvotes: 3

Related Questions