c ++指针向量中的垃圾值 [英] c++ garbage values in vector of pointer
问题描述
当我这样做:
for(i = 0; i // create objectA here
vectorA.push_back(objectA);
pvectorA.push_back(& vectorA [i]);
}
pvectorA的一些元素是垃圾。但是,当我这样做:
for(i = 0; i // create objectA这里
vectorA.push_back(objectA);
}
for(i = 0; i pvectorA.push_back(& vectorA [i]);
}
一切正常。为什么会发生?
先说明:
在向量结尾处,在当前最后一个元素之后添加一个新元素。将val的内容复制(或移动)到新元素。
这有效地将容器大小增加了一个,这会导致自动重新分配已分配
然后关于迭代器的有效性:
如果发生重新分配,所有与容器相关的迭代器指针
因此,当您向向量中添加对象时,指向该向量中的对象的所有指针可能会变为无效 - 除非您保证向量具有 std :: vector :: reserve
的足够能力
p>
无效意味着指针不再指向有效的对象,并取消引用它将具有未定义的行为。
在后面的代码中,在存储指针之后,不要向指向的向量添加对象,因此指针是有效的。
When I do:
for(i=0; i<size; i++){
//create objectA here
vectorA.push_back(objectA);
pvectorA.push_back(&vectorA[i]);
}
some elements of pvectorA is garbage. However when I do:
for(i=0; i<size; i++){
//create objectA here
vectorA.push_back(objectA);
}
for(i=0; i<size; i++){
pvectorA.push_back(&vectorA[i]);
}
Everything is okay. Why is it happens?
Read the documentation of std::vector::push_back
First the description:
Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.
This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.
Then about validity of iterators:
If a reallocation happens, all iterators, pointers and references related to the container are invalidated.
So, when you add an object to the vector, all the pointers pointing to objects in that vector may become invalid - unless you've guaranteed that the vector has enough capacity
with std::vector::reserve
.
Invalid means that the pointer no longer points to a valid object and dereferencing it will have undefined behaviour.
In the latter code, you never add objects to the pointed-to vector after you've stored the pointers, so the pointers are valid.
这篇关于c ++指针向量中的垃圾值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!