This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: static map in a base class?


Hi Colin,

A's static theMap will be initialized by the time main is called.

B's static testB will be initialized by the time main is called. But note, it DEPENDS on A's static theMap being initialized BEFORE it gets initialized, and MAY BE initialized BEFORE A's static theMap is initialized! There is NO guarantee of order-of-initialization between different compile modules.

One way to alleviate the cross-module initialization conundrum is via:
// In a.cpp
class A
{
public:
A() ;
~A() ;
void doSomething() ;
static std::map<int,std::string>& getMap();
};

// In a.h
std::map<int,std::string>& A::getMap() {
static std::map<int,std::string> A::theMap ;
return theMap;
}

The trick works because getMap's static theMap is GUARANTEED to be initialized the first time the routine is accessed. Regardless of cross-module order-of-initialization dependencies.

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

Some other nits:
You didn't #include <string>.
You didn't #include <utility>, for the pair template.
Your sentinels, e.g. __A_H__, are illegal. I recommend a_h_ONCE instead.

Sincerely,
--Eljay


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]