Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...