how to populate a static member map?

Suppose I have in MyClass.hpp

#include <string>
#include <map>

using namespace std;
class MyClass {
private:
map<string,int> g_mymap;
};

and in MyClass.cpp

map<string,int> MyClass::g_mymap;

-----------------------------------------------

How do I populate g_mymap with values that never change from run to run?

I thought about checking in the constructor of MyClass to see if g_mymap is empty before populating it, but this wouldn't be sufficient if I have static member functions which use g_mymap (ie static member functions may be called without any constructors ever being called).

Any suggestions?

Write a static method in MyClass that returns the map.

Then it will get constructed on demand.

1
2
3
4
5
6
7
8
9
10
11
12
13
typedef std::map<std::string, int> MyMap;

static MyMap GetMap() {
    static bool once = false;
    static MyMap the_map;

    if( !once ) {
        // fill out map
        once = true;
    }

    return the_map;
}


Note: not thread safe of course.
jsmith,

Thanks for your suggestion... ...I was thinking about putting a wrapper around it.

This just seems like a lame interaction/limitation in static member variables and initialization order...

I guess if I return a const reference to avoid a copy construct, it would work:

1
2
3
static const MyMap& GetMap() {
  // ...
}


If I have to use a wrapper, maybe I should just provide the mapping service:

1
2
3
4
5
6
7
8
9
10
11
class MyClass {
    static int GetValueFromMap( const string& key )
    {
        static MyMap theMap;

        if ( theMap.size()==0 ) {
          // fill map
        } 
        return theMap[key];       // being lazy: not checking for errors
    }
};
Last edited on
Oh, yes, returning by const reference would be preferable.
Topic archived. No new replies allowed.