指针 vector 中的 C++ 垃圾值

标签 c++ pointers vector stl push-back

当我这样做时:

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/

相关文章:

c++ - 学习c++11智能指针,它不会让我像指针一样使用隐式转换吗?

c++ - 如何在多个函数中使用同一个多维数组?

c++ - 从包含 Int 和 Char 数据类型的文件中读取

objective-c - 关于 Objective-C 中的指针

c++ - 是否有可能有一个指针文字?

c++ - 调用模板化成员函数与模板化全局函数在通用工厂中创建对象

c++ - 简单检查 dynamic_cast c++

r - 用数据帧中的值替换向量的元素

c++ - unistd read() 不起作用

c++ - 从不兼容类型 'int *'(又名 'value_type')分配给 'std::__1::vector<int, std::__1::allocator<int>>'