Topic: Question about npos constant in basic_string class


Author: Matt Austern <austern@sgi.com>
Date: 1999/10/14
Raw View
Gawain Bolton <gbolton@club-internet.fr> writes:

> I have a question concerning the npos constant in the basic_string
> class.  What I want to know is why is this constant a static variable?
> It is shown in section 21.3 [lib.basic.string] as follows:
>
> static const size_type npos = -1;
>
> I was wondering why this isn't defined as just an anonymous enumerated
> constant as follows:
>
> enum
> {
>     npos = (size_type) (-1)
> };
>
> The problem with it being defined as a static data member is that the
> constant may not be initialized before it is used.  This could happen if
> static objects use the basic_string class.

This is an object of a POD type with static storage duration
initialized with a constant expression, therefore (3.6.2/1) it is
initialized before any dynamic initialization takes place.  There's no
way to write code, even in the constructors of static objects, that
will run before basic_string<>::npos gets initialized.

(On any real implementation I would expect basic_string<>::npos to get
initialized at link time, but of course the C++ standard can't say so.
All it can say is that it gets initialized before any dynamic
initialization.)



[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Gawain Bolton <gbolton@club-internet.fr>
Date: 1999/10/14
Raw View
I have a question concerning the npos constant in the basic_string
class.  What I want to know is why is this constant a static variable?
It is shown in section 21.3 [lib.basic.string] as follows:

static const size_type npos = -1;

I was wondering why this isn't defined as just an anonymous enumerated
constant as follows:

enum
{
    npos = (size_type) (-1)
};

The problem with it being defined as a static data member is that the
constant may not be initialized before it is used.  This could happen if
static objects use the basic_string class.

This question may have been asked already - unfortunately I am only able
to read this newsgroup occasionally - in which case I apologize in
advance...

Thanx,

Gawain
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]