向量中我的对象的地址发生了变化 [英] The address of my object in a vector changes
问题描述
我用 A
个对象填充了一个向量,然后将这些对象的地址存储在 multimap
[1]中,但是打印消息显示对矢量中存储的对象的引用已更改[2]。你明白为什么吗?
I filled a vector with A
objects, then stored these objects address in a multimap
[1], but the print message shows that the reference to the object stored in the vector changed [2]. Do you see why? and how avoid any changes.
//[1]
vector<A> vec;
multimap<const A*, const double > mymultimap;
for (const auto &a : A) {
double val = a.value();
vec.push_back(a);
mymultimap.insert(std::pair<const A*, const double >( &vel.back(), val));
// displaying addresses while storing them
cout<<"test1: "<<&vec.back()<<endl;
}
//[2]
// displaying addresses after storing them
for(auto &i : vec)
cout << "test2: " << &i <<endl;
结果:
test1: 0x7f6a13ab4000
test1: 0x7f6a140137c8
test2 :0x7f6a14013000
test2 :0x7f6a140137c8
推荐答案
您正在在中调用
vec.push_back(a)
/ code>循环。因此,如果空间不足,向量可能会重新分配基础数组。因此,如果以前的元素的地址被复制到新的内存位置,则该地址不再有效。
You are calling vec.push_back(a)
within your for
loop. Therefore the vector may re-allocate the underlying array if it runs out of space. Therefore the address of the previous elements are no longer valid if they were copied to the new memory location.
例如,您分配了3个元素并存储了它们的地址。向后推第四个元素后,必须重新分配向量。这意味着将前3个元素复制到新位置,然后在其后添加第4个元素。因此,您为前3个地址存储的地址现在无效。
For example say you allocated 3 elements and stored their addresses. After pushing back a 4th element the vector has to reallocate. That means the first 3 elements will be copied to a new location, then the 4th will be added after that. Therefore the address you had stored for the first 3 are now invalid.
这篇关于向量中我的对象的地址发生了变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!