Connecting Tech Pros Worldwide Forums | Help | Site Map

pointer to an elment in a stl vector

Eric
Guest
 
Posts: n/a
#1: Jul 22 '05
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[i])?
If the vector increases in size could it invalidate that pointer?

Flzw
Guest
 
Posts: n/a
#2: Jul 22 '05

re: pointer to an elment in a stl vector



"Eric" <emedlin@myrealbox.com> wrote in message
news:a6af27e.0408181308.17a2a019@posting.google.co m...[color=blue]
> 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[i])?
> If the vector increases in size could it invalidate that pointer?[/color]

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


Kai-Uwe Bux
Guest
 
Posts: n/a
#3: Jul 22 '05

re: pointer to an elment in a stl vector


Eric wrote:
[color=blue]
> 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[i])?[/color]

Yes. AFAIK, it is blessed by the standard.

[color=blue]
> If the vector increases in size could it invalidate that pointer?[/color]

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
Jeff Flinn
Guest
 
Posts: n/a
#4: Jul 22 '05

re: pointer to an elment in a stl vector



"Flzw" <flownz@wanadoo.fr> wrote in message
news:cg0h87$b91$1@news-reader2.wanadoo.fr...[color=blue]
>
> "Eric" <emedlin@myrealbox.com> wrote in message
> news:a6af27e.0408181308.17a2a019@posting.google.co m...[color=green]
> > 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[i])?
> > If the vector increases in size could it invalidate that pointer?[/color]
>
> not if you stick to adding elements, if you plan on erasing some, you[/color]

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

[color=blue]
> shouldn't use it, switching to list might help.[/color]


Jeff F


Rolf Magnus
Guest
 
Posts: n/a
#5: Jul 22 '05

re: pointer to an elment in a stl vector


Kai-Uwe Bux wrote:
[color=blue]
> Eric wrote:
>[color=green]
>> 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[i])?[/color]
>
> Yes. AFAIK, it is blessed by the standard.
>
>[color=green]
>> If the vector increases in size could it invalidate that pointer?[/color]
>
> Yes. The vector might be reallocated to accommodate for new elements.
> This will invalidate all iterators and pointers derived from
> iterators.[/color]

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

Closed Thread