I have a class which contains a static member, a map of strings to function pointers. This map is intended to be populated once with a static set of mappings, and will not subsequently be modified.
My question is, how can I ensure the map is not accessed before it is initialised? My code currently looks something like this:
class MyClass
{
static MapType s_myMap;
public:
static const MapType& getTheMap()
{
if (s_myMap.empty())
{
// Populate the map
}
return s_myMap;
}
};
which works fine for external clients of MyClass, but doesn’t prevent internal class members from directly accessing the private map before it has been initialised.
To address that problem I am thinking of making the map local to the getter method:
class MyClass
{
public:
static const MapType& getTheMap()
{
static MapType s_myMap;
if (s_myMap.empty())
{
// Populate the map
}
return s_myMap;
}
};
Is that a good idea, or is there a better way of achieving this?
Moving the static into the function will solve any order of
initialization problems, but it may leave you with an order of
destruction one. In many cases, it’s preferable to use a pointer and
dynamic allocation, so that the map is never destructed.
As for initializing it, I often use the two iterator constructor, so
that I can make the map itself const. To do this, just define a
structwith a conversion operator, something like: