Vector of children ofNodes


I need two ofNode vector, where every ofNode in one vector is a parent to one ofNode in the other.

ofNode node = ofNode();

ofNode childNode = ofNode();

This works fine for the first pair, but when the second node gets pushed (the second time row 2 is run), the destructor for the first node is called, which means that the child-parent pointers are dereferenced, leading to null pointers further down in the code.

How do I work around this?


you need to either use a vector of some kind of pointer of node, like a unique_ptr or shared_ptr or reserve the vector to the total amount of nodes you are going to put in it so it never resizes

Ok, thank you, I will look into using those kinds. Can you explain or refer to documentation as to why the object is destroyed when pushing an element to the back of the vector?

when you push to a vector it might need to resize to hold all the objects contiguosly in memory, when that happens it needs to copy every object to a new location and destroy the old ones that messes up the parenting which depends on the memory address the parent node