C ++ refers to push_back element changes to std :: vector

I'm not sure what to do with this - please tell me what happened to the code below. I modified my code to reduce it to the simplest conditions. There is std :: vector with a bunch of MyNode objects. The first step is to get a permanent link 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 second node is inserted, as shown below:

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

Exactly the vector :: push_back call, the value of currData is changing! I just do not understand. How to insert a new node vector into a vector, change the value of the data link of the first node? !! Note that the value does not change when the 2nd node is "created", but during the insert operation in std :: vector. I mean, I suppose std :: vector might shuffle some memory, but should this not change the correctness of the link ??

Compiler = VS 2012

Thanks guys. Very much appreciated.

+6
source share
3 answers

How to insert a new node vector into a vector, change the value of the data link of the first node? !!

Because the elements of the vector are stored in an adjacent array. When there is more space in the array, all elements are moved to a larger one, invalidating all iterators, pointers, and references to them.

I assume that std :: vector might shuffle some memory, but should this not change the correctness of the link ??

Sure. A link refers to a specific object at a specific address; it does not track an object if it moves.

If you need stable links, use deque ; or (if possible) use reserve to set the vector capacity large enough to contain anything you could add. Links are invalid only when redistribution is necessary, and this only happens when you try to go beyond the current capacity.

Alternatively, you can save the index of the object, not a link to it.

+14
source

When you add a new element to a vector, the data in it can be redistributed to fit the new element. This means that references and pointers to elements (and their members) will be invalid.

+3
source

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

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

Source: https://habr.com/ru/post/956706/


All Articles