指向向量内存丢失的指针

Pointer to Vector Memory Loss

我遇到了指针向量的问题... 我知道问题可能是什么:

当我创建一个指向向量的指针时,该指针在堆上保留向量的大小。所以这基本上意味着,指针现在指向向量的内存而内部没有任何东西......当我现在调整或推回向量时,指针现在仍然指向向量的整个内存还是仅指向具有的内存一开始分配了吗?

我也想知道,如果有一些技巧可以解决这个问题(如果我认为是真的)。 "vector.reserve(n)" 是实现此目的的方法吗?或者我可以做些什么来在初始化后将指针内存地址覆盖到向量?

"When I create a pointer to a vector, the pointer reserves the size of the vector on the heap.

不,不是! 当你创建一个指向向量的指针时,你就有了一个指针。而已。它还没有指向任何东西,它肯定没有为你保留任何 "heap memory"。

您仍然需要实际创建将指向的向量。

std::vector<int>* ptr1;                            // just a pointer;
ptr1 = new std::vector<int>();                     // there we go;
delete ptr1;                                       // don't forget this;

auto ptr2 = std::make_shared<std::vector<int>>();  // alternatively...

您知道,您很少需要动态分配容器。通常你只想以通常的方式构造它:

std::vector<int> v;

就是这样。不需要指点。


When i now resize or pushback the vector, will the pointer now still point to the whole memory of the vector or just the memory which has been allocated at the beginning?

不管你如何constructed/allocated它,矢量本身永远不会自发移动(只有它在内部为你管理的动态内存),所以你不需要担心这个。


I also want to know, if there are some tricks you can do to fix that

不需要,因为没有什么要修复的。


Is the "vector.reserve(n)" a method of accomplishing this?

理论上,如果这 一个问题(实际上不是),那么,是的,这可能构成解决方案的基础。

Vector 是 class,它具有指向使用堆中连续内存块的 vector 元素的内部指针。对于所有保留向量的元素足够长(capacity() 方法) 因此,如果您创建矢量(在本地范围的堆栈中或在堆中 - 无关紧要),它会创建此布局

[ vector   [ ptr-to-data ] ] --> HEAP: [ 1 ][ 2 ][ 3 ]

vector<int> v1(3); // whole vector instance in the stack 
vector<int> *pv2 = new vector<int>(3); // pointer to vector in the heap

这 2 个向量实例中的每一个都有指向其在堆中的元素的指针

Vector 在内部管理其指向数据的指针。 当您 push_back() 的元素多于当前的 .capacty() 时,它将重新分配新的连续内存块并复制构造或将所有旧元素移动到这个新块。