Question

I have a fairly complex scenario, so I am trying to distill this down to the basic issue.

I have 3 classes (simplified here):

class Base {
protected:
    std::map <unsigned int, Node*> nodes;
}

class Node {
protected:
    std::map <unsigned int, Leaf*> leaves;
}

class Leaf {
protected:
    myDataStruct myData;
}

These classes represent a 3-level tree consisting of a base, some number of intermediary nodes in a std::map<int,ptr*>, and some number of leaves per node, also as a std::map<int,ptr*>. This tree is generated and updated dynamically in an update thread.

I have another thread that renders data from these nodes, at a much slower rate than the updates, so I prefer to keep the update action separate from the rendering. I do not render all of the data on every loop of the render thread either.

My original idea was to register that I wanted to render data from a leaf by calling a function that stores a pointer to the data in the leaf:

void MyRenderClass::registerData(int* dataPointer) {
    // store dataPointer in MyRenderClass
    myStoredDataPointer = dataPointer;
}

Then during the render thread loop, I use that data pointer to render the data.

So, the question is: Is this safe? I can handle the case where the leaf or node is deleted by un-registering the data in the respective destructors. What I really want to know is, will that pointer stay the same as the tree is updated and as new nodes and leaves are added to it? Will the std::map rearrange or move pointers as it is modified?

On a related note, can I safely store pointers to the parent nodes/base in the leaves/nodes so I can traverse the tree from leaf->base?

I hope this makes sense. I thought this seemed ok at first, but I want to verify before I go further down this path. The example is slightly contrived, as the entire code base is much too large to grok.

Was it helpful?

Solution

The important question here is:

Will the std::map rearrange or move pointers as it is modified?

std::map guarantees that iterators, references and pointers to its objects will remain valid as long as that object remains in the map. So you can safely store a pointer, as long as you don't remove the object it points to.

Note that not all containers give this guarantee; for example, vector will move its elements when it exceeds its capacity and has to allocate a new block of memory, in order to keep the elements in a contiguous array. (But even then, if you're storing pointers, then the objects they point to won't move).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top