问题描述
我不知道该怎么做 - 请告诉我下面的代码有什么问题.我修改了我的代码以将其简化为最简单的术语.有一个带有一堆 MyNode 对象的 std::vector.第一步是获取对这些节点之一的数据元素之一的常量引用(Data m_data) - 在下面的示例中,在插入第二个节点之前只有一个节点,如下所示:
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);
恰好在 vector::push_back 调用时,currData 的值发生了变化!!我只是不明白.向向量中插入新节点如何改变对第一个节点数据的引用?!!请注意,该值不会在创建"第二个节点时更改 - 但在插入操作到 std::vector 时更改.我的意思是,我想 std::vector 可能会重新整理一些内存,但这不应该改变引用吗??
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??
编译器 = VS 2012
Compiler = VS 2012
谢谢各位.非常感谢.
推荐答案
在vector中插入一个新节点如何改变对第一个节点数据的引用?!!
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.
我想 std::vector 可能会重新整理一些内存,但这不应该改变引用吗??
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.
如果你需要稳定的引用,那么使用deque
;或者(如果可能)使用 reserve
将向量的容量设置为足够大以包含您可能添加的所有内容.引用仅在需要重新分配时无效,并且仅在您尝试超出当前容量时才会发生.
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.
这篇关于当 push_back 新元素到 std::vector 时,C++ 引用发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!