This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: static map in a base class?
- From: Eljay Love-Jensen <eljay at adobe dot com>
- To: Colin Law <c dot law at elec dot gla dot ac dot uk>, gcc-help at gcc dot gnu dot org
- Date: Fri, 01 Nov 2002 07:21:20 -0600
- Subject: 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