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 *>;
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's not a leak as such but you'll have a hard time debugging your
problem with purify as it will show up as a leak and you could have
trouble working out which ones are valid and which ones are not. I
personally prefer not to have the idiom above.
- Is the code above a candidate for refactoring ?
A quick change would be to convert
Is it a essential improvement ?
Do not have a loose static instance because you cannot control
initialisation order. But the best solution in my opinion is to use a
function that has the static member and returns it by reference. Here
there is some control as the member will not be initialised until the
function is first called. If it needs other singletons to already exist
it will call their appropriate function and you'll be safe as long as
there are no circular references.
In addition, should any constructor throw an exception it will be
Finally, in a multi-threaded environment, there should be no problems
with race conditions using a static member (compilers have to be
compliant with this though), whereas there might be using a static
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]