取消引用指向访问元素的向量指针

2021-12-21 00:00:00 vector c++ dereference

如果我在 C++ 中有一个指向向量的指针:

If i have in C++ a pointer to a vector:

vector<int>* vecPtr;

我想访问向量的一个元素,然后我可以通过取消引用向量来做到这一点:

And i'd like to access an element of the vector, then i can do this by dereferncing the vector:

int a = (*vecPtr)[i];

但是这种取消引用实际上会在堆栈上创建我的向量的副本吗?假设向量存储 10000 个整数,是否会通过取消引用 vecPtr 来复制 10000 个整数?

but will this dereferencing actually create a copy of my vector on the stack? let's say the vector stores 10000 ints, will by dereferencing the vecPtr 10000 ints be copied?

谢谢!

推荐答案

10000 ints 不会被复制.取消引用非常便宜.

10000 ints will not be copied. Dereferencing is very cheap.

为清楚起见,您可以重写

To make it clear you can rewrite

int a = (*vecPtr)[i];

作为

vector<int>& vecRef = *vecPtr; // vector is not copied here
int a = vecRef[i];

此外,如果您担心存储在 vector 中的整个数据将位于堆栈中,则使用 vector* 而不是 vector 以避免这种情况:情况并非如此.实际上,堆栈上只使用了固定数量的内存(大约 16-20 字节,具体取决于实现),与 vector 中存储的元素数量无关.vector 本身分配内存并将元素存储在堆上.

In addition, if you are afraid that the whole data stored in vector will be located on the stack and you use vector<int>* instead of vector<int> to avoid this: this is not the case. Actually only a fixed amount of memory is used on the stack (about 16-20 bytes depending on the implementation), independently of the number of elements stored in the vector. The vector itself allocates memory and stores elements on the heap.

相关文章