当将新元素push_back到std :: vector时,C ++引用发生更改 [英] C++ reference changes when push_back new element to std::vector

查看:668
本文介绍了当将新元素push_back到std :: vector时,C ++引用发生更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道该怎么做 - 请告诉我下面的代码有什么问题。我修改了我的代码,以减少到最简单的术语。有一个std :: vector有一堆MyNode对象。第一步是获得对这些节点(数据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);

正是向量:: 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??

Compiler = VS 2012

Compiler = VS 2012

谢谢你们。非常感谢。

推荐答案


如何将一个新节点插入向量将值引用更改为第一个节点的数据?!!

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 ++引用发生更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆