This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: STL and Mozilla XPCOM
- From: Martin Sebor <sebor at roguewave dot com>
- To: libstdc++ at gcc dot gnu dot org
- Date: Tue, 19 Feb 2002 14:54:52 -0700
- Subject: Re: STL and Mozilla XPCOM
- Organization: Rogue Wave Software, Inc.
- References: <200202192137.NAA06568@atrus.synopsys.com>
- Reply-to: libstdc++ at gcc dot gnu dot org
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