当我这样做时:
for(i=0; i<size; i++){
//create objectA here
vectorA.push_back(objectA);
pvectorA.push_back(&vectorA[i]);
}
pvectorA 的一些元素是垃圾。但是当我这样做时:
for(i=0; i<size; i++){
//create objectA here
vectorA.push_back(objectA);
}
for(i=0; i<size; i++){
pvectorA.push_back(&vectorA[i]);
}
一切正常。为什么会这样?
最佳答案
阅读 std::vector::push_back 的文档
首先是描述:
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.
然后关于迭代器的有效性:
If a reallocation happens, all iterators, pointers and references related to the container are invalidated.
因此,当您向 vector 中添加一个对象时,指向该 vector 中对象的所有指针都可能变为无效 - 除非您通过 std 保证该 vector 具有足够的
.容量
::vector::reserve
无效 意味着指针不再指向有效对象并且取消引用它将会有未定义的行为。
在后面的代码中,在存储指针后,您永远不会将对象添加到指向的 vector 中,因此指针是有效的。
关于指针 vector 中的 C++ 垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33366877/