Re: static class variable allocated at heap
a project I'm involved in has code in the form:
static std::map<QCString, toConnectionProvider *> *Providers;
A provider can register itself in the map:
void toConnectionProvider::addProvider(const QCString &provider)
Provider = provider;
(*Providers)[Provider] = this;
and there is a member function which checks if the map is allocated.
Providers = new std::map<QCString, toConnectionProvider *>;
Wouldn't it be more nature to call it getProviderMap, and have
it return a pointer to the map?
I have the following questions:
- AFAIK Providers is never "deleted" until program exit and usually
I expect a new/delete pair for dynamic memory allocation.
So I guess the idiom above(static class variable allocated at heap)
is not kosher ?!
It depends. In this case, the map is really a singleton, and
it's usual for a singleton to never be destructed. (I tend to
refer to such objects as "pseudo-static" objects.)
- Is the code above a candidate for refactoring ?
A quick change would be to convert
Is it a essential improvement ?
It depends. Using the function avoids order of initialization
issues if a static object registers itself. It may also cause
threading issues in a multithreaded environment.
Note that if you want destruction, you can make the map a local
static variable in its getter function.
- Another idea would be to make a separate class
toConnectionProviderManager which stores the providers in a container.
Is it a good idea ?
There's no fixed rule. If the map is simple, as it is here, I
generally go they way you've gone here, with a couple of static
member functions to handle registration, lookup, and if
necessary, managing the singleton object. If the map is not
just a standard class, and has significant behavior, I'll make a
separate class of it.
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]