How can inserting a new node to the vector change the value reference to the data of the first node?!!
Because the elements of a vector are stored in a contiguous array. When there's no more room in the array, all of the elements are moved to a larger one, invalidating all iterators, pointers and references to them.
I suppose std::vector may reshuffle some memory, but that shouldn't change the reference right??
Of course it would. A reference refers to a particular object at a particular address; it does not track the object if it's moved.
If you need stable references, then use deque
; or (if possible) use reserve
to set the vector's capacity large enough to contain everything you might add. References are only invalidated when reallocation is needed, and that only happens when you try to grow beyond the current capacity.
Alternatively, you could store the index of the object, rather than a reference to it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…