pointer to an elment in a stl vector

E

Eric

Say I have vector<int> tmp. I then call a function that needs a
pointer to an int in tmp. Is it wise to pass the function &(tmp)?
If the vector increases in size could it invalidate that pointer?
 
F

Flzw

Eric said:
Say I have vector<int> tmp. I then call a function that needs a
pointer to an int in tmp. Is it wise to pass the function &(tmp)?
If the vector increases in size could it invalidate that pointer?


not if you stick to adding elements, if you plan on erasing some, you
shouldn't use it, switching to list might help.
 
K

Kai-Uwe Bux

Eric said:
Say I have vector<int> tmp. I then call a function that needs a
pointer to an int in tmp. Is it wise to pass the function &(tmp)?


Yes. AFAIK, it is blessed by the standard.

If the vector increases in size could it invalidate that pointer?

Yes. The vector might be reallocated to accommodate for new elements.
This will invalidate all iterators and pointers derived from iterators.


Best

Kai-Uwe Bux
 
J

Jeff Flinn

Flzw said:
Eric said:
Say I have vector<int> tmp. I then call a function that needs a
pointer to an int in tmp. Is it wise to pass the function &(tmp)?
If the vector increases in size could it invalidate that pointer?


not if you stick to adding elements, if you plan on erasing some, you


Wrong! std::vector::push_back CAN cause invalidation, and most certainly
will if the capacity of the vector is insufficient.

shouldn't use it, switching to list might help.


Jeff F
 
R

Rolf Magnus

Kai-Uwe Bux said:
Eric said:
Say I have vector<int> tmp. I then call a function that needs a
pointer to an int in tmp. Is it wise to pass the function &(tmp)?


Yes. AFAIK, it is blessed by the standard.

If the vector increases in size could it invalidate that pointer?

Yes. The vector might be reallocated to accommodate for new elements.
This will invalidate all iterators and pointers derived from
iterators.


And of course also pointers not derived from iterators. It might
invalidate all pointers to any elements of the vector.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top