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

时光怂恿深爱的人放手 提交于 2019-12-17 19:10:57

问题


I am not sure what to make of this - please tell me what's wrong with the code below. I modified my code to reduce it to the simplest terms. There is a std::vector with a bunch of MyNode objects. The first step is to get a constant reference to one of the data elements of one of these nodes (Data m_data) - in the example below, there is only one node before the 2nd node is inserted as seen below:

const cv::Data& currData = m_nodesVector[currIndex].GetData();
MyNode node(...);
m_nodesVector.push_back(node);

At exactly the vector::push_back call, the value of currData changes!! I just don't get it. How can inserting a new node to the vector change the value reference to the data of the first node?!! Note that the value doesn't change upon "creating" the 2nd node - but upon the insertion operation into the std::vector. I mean, I suppose std::vector may reshuffle some memory, but that shouldn't change the reference right??

Compiler = VS 2012

Thanks guys. Much appreciated.


回答1:


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.




回答2:


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.




回答3:


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

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



回答4:


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.



来源:https://stackoverflow.com/questions/19587738/c-reference-changes-when-push-back-new-element-to-stdvector

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