Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

c++ - Dereference vector pointer to access element

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

To make it clear you can rewrite

int a = (*vecPtr)[i];

as

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...