Re: Initializing a map...
Jeff Schwab wrote:
James Kanze wrote:
[...]
I often find it worthwhile to define a special structure for
this, something along the lines of:
typedef std::map< std::string, double > Map ;
struct MapInit
{
char const* key ;
double value ;
operator Map::value_type() const
{
return Map::value_type( std::string( key ), value ) ;
}
} ;
Is the key stored as a char const* so that construction of the
initializers does not require any run-time overhead? Does
MapInit count as a POD type, and is there benefit to using POD
initializers?
In this case, the key is stored as a char const* more by habit
than anything else. The underlying reason is that doing so
allows static initialization, which in turn avoids any possible
order of initialization issues. If the map and the table are
defined in the same file (which is the case here), the order of
initialization is well defined, and there is no problem. If the
initialization table is defined in another translation unit,
however (e.g. because it is machine generated), then static
initialization means that it is still guaranteed to work;
otherwise, you need some special logic to ensure that the table
is initialized before the map. Similarly, if you expect the map
to be used from constructors of other static objects, and use
the singleton idiom to construct it, unless the initialization
table uses static initialization, you might have an order of
initialization problem.
And of course, if the table is small enough to be initialized by
hand, I'll use std::find_if on it, rather than bother creating a
map. In such cases, ensuring static initialization also avoids
any order of initialization problems, without the need of a
singleton.
(FWIW: ensuring static initialization is practically the only
time I use char[] or char* instead of std::string.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34