Say I have this:
Object *myObject;
std::vector<Object> objects(99);
....
myObject = &objects[4];
Would it be safe to assume that myObject’s pointer will always be valid no matter how big objects[] gets and if I remove some, as long as I do not ever erase() the actual object pointed to by myObject? Or does it work differently? If the above does not work, how else could I achieve this? It’s because in my design, I want a child to have a pointer to its parent, which is assigned by the parent when the child is added, however the parents are in a std::vector, I need random access. Would a std::list be better in my case?
Thanks
If the vector fills up its allocated space and you try to insert more, it needs to re-allocate its storage, and that will involve copying over the objects and destroying the old storage, which would invalidate the pointer you’re keeping around – so no, this is not good enough.
std::list would work fine, since it doesn’t rely on continuous storage, but you lose the ability to do quick random access. Alternatively, you can store pointers to your Objects in your collection, in which case you can just take out that element, and the pointer will remain valid until you free that memory in your code – but you will need to handle that yourself at some point.
Another option might be a deque; while deque iterators are invalidated by
push_back, direct references to elements (like the pointer you’re using here) remain valid.