STL and Mozilla XPCOM
Martin Sebor
sebor@roguewave.com
Tue Feb 19 13:55:00 GMT 2002
Joe Buck wrote:
>
> > i'm having a problem with a "&*something" idiom in the GNU STL,
> > which occurs here..
>
> It's not specific to the GNU implementation. You'll find common uses
> of such code; a number of authors writing on the STL recommend its use.
>
> > .. maybe someone could explain the rationale behind this idiom?
>
> An iterator is not necessarily a pointer, but in certain contexts
> (e.g. vectors) we are promised that the elements are in contiguous
> memory. To get to this memory with an ordinary pointer, &*iterator
> is used. For example, let's suppose I use a vector<char> named v to hold
> a null-terminated string, and then I want to pass that string to a
> C function, such as strcpy. I can't use v.begin() as the argument,
> as it is not necessarily a pointer. What I can use is &*v.begin() .
Right, except that if the iterator's value_type defines operator&()
in an unconventional way or makes it inaccessible, both of which
it is currently allowed to do, this idiom breaks. A safer approach
would be to use reinterpret_cast like so:
extern Iterator __cur;
typedef typename iterator_traits<Iterator>::pointer Pointer;
construct (reinterpret_cast<Pointer>(
&reinterpret_cast<char&>(*__cur)),
*__first);
This must work since the iterator's operator*() is required to return
value_type&.
Regards
Martin
More information about the Libstdc++
mailing list