Initialize a static private map as empty

Header:

class XXX {
private:
    static std::map<X,Y> the_map; // declares static member
// ...

Implementation file:

std::map<X,Y> XXX::the_map; // defines static member

That will insert a constructor call for your map into your program initialization code (and a destructor into the cleanup). Be careful though - the order of static constructors like this between different translation units is undefined.


How about this (if I understand you correctly):

std::map<T,T2> YourClass::YourMember = std::map<T,T2>();

If you declare it in the class definition, then you have to define it in the implementation:

--- test.h ---

// includes and stuff...
class SomeClass
{
    private:
        static std::map<int,std::string> myMap;
};

--- test.cpp ---

std::map<int,std::string> SomeClass::myMap; // <-- initialize with the map's default c'tor

You can provide an initialization, too:

std::map<int,std::string> SomeClass::myMap = std::map<int,std::string>(myComparator);

Tags:

C++

Map