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?