取消引用指向访问元素的向量指针
如果我在 C++ 中有一个指向向量的指针:
vector<int>* vecPtr;
并且我想访问该向量的元素,那么我可以通过取消引用该向量来做到这一点:
int a = (*vecPtr)[i];
但是这种取消引用实际上会在堆栈上创建我的向量的副本吗?假设向量存储 10000 个整数,通过取消引用 vecPtr 是否会复制 10000 个整数?
谢谢!
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];
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?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
10000 个
int
不会被复制。取消引用非常便宜。为了清楚起见,您可以重写
为
此外,如果您担心存储在
vector
中的整个数据将位于堆栈上,并且您使用vector*
而不是vector
来避免这种情况:事实并非如此。实际上,堆栈上仅使用固定数量的内存(大约 16-20 个字节,具体取决于实现),与
vector
中存储的元素数量无关。vector
本身分配内存并将元素存储在堆上。10000
int
s will not be copied. Dereferencing is very cheap.To make it clear you can rewrite
as
In addition, if you are afraid that the whole data stored in
vector
will be located on the stack and you usevector<int>*
instead ofvector<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.不,不会复制任何内容;取消引用只是告诉 C++ 您想要在向量上调用operator[],而不是在指针、
vecPtr
上调用。如果您没有取消引用,C++ 将尝试查找在std::vector*
类型上定义的运算符[]。这可能会让人非常困惑,因为
operator[]
是为所有指针类型定义的,但它相当于偏移指针,就好像它指向vector
数组一样。如果您实际上只在那里分配了一个向量,那么对于0
以外的任何索引,表达式的计算结果将是对垃圾的引用,因此您将得到段错误或您不希望得到的结果。一般来说,通过指针访问向量是一件痛苦的事情,而且
(*vecPtr)[index]
语法很尴尬(但比vecPtr->operator[](index)
更好代码>)。相反,您可以使用:这实际上会检查范围,与
operator[]
不同,因此如果您不想为检查索引是否在范围内而付出代价,那么您就只能使用(*vecPtr)[]
。No, nothing will be copied; dereferencing just tells C++ that you want to invoke operator[] on the vector, not on your pointer,
vecPtr
. If you didn't dereference, C++ would try to look for an operator[] defined on thestd::vector<int>*
type.This can get really confusing, since
operator[]
is defined for all pointer types, but it amounts to offsetting the pointer as though it pointed to an array ofvector<int>
. If you'd really only allocated a single vector there, then for any index other than0
, the expression evaluates to a reference to garbage, so you'll get either a segfault or something you did not expect.In general, accessing vectors through a pointer is a pain, and the
(*vecPtr)[index]
syntax is awkward (but better thanvecPtr->operator[](index)
). Instead, you can use:This actually checks ranges, unlike
operator[]
, so if you don't want to pay the price for checking if index is in bounds, you're stuck with(*vecPtr)[]
.