C++ reference changes when push_back new element to std::vector

半世苍凉 提交于 2019-11-28 09:26:54

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.

When you add a new item to a vector, the data in it may be reallocated to fit the new item. This means that references and pointers to the items (and their members) will be invalid.

You can update the pointer, when it is moved, through the move-constructor:

A(A&& a): b(a.b) { b.ptr  = this; };

Visit http://www.cplusplus.com/reference/vector/vector/push_back/

When you try to add new item it will check for next adjacent memory is free or not. If free then new item added to next available location else first vector reallocated and new item added.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!