Reputation:
I have a static map
that is a private
data member. How do I initialize it in the implementation file so that it's initial containers are empty? It is not const
. It is important that nothing is in this container at start.
Upvotes: 10
Views: 33641
Reputation: 5080
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);
Upvotes: 3
Reputation: 84169
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.
Upvotes: 13
Reputation: 35803
How about this (if I understand you correctly):
std::map<T,T2> YourClass::YourMember = std::map<T,T2>();
Upvotes: 8