Re: question re. usage of "static" within static member functions of
a class
On Sep 13, 5:37 am, "Chris M. Thomasson" <n...@spam.invalid> wrote:
"James Kanze" <james.ka...@gmail.com> wrote in message
news:ecb6784b-9cc7-49d7-847b-30f765b2006b@r9g2000yqa.googlegroups.com...>
On Sep 7, 9:02 pm, Francesco <entul...@gmail.com> wrote:
[...]
Not knowing the requirements, it's hard to say. My usual
implementation is:
class Data
{
private:
static Data* ourInstance ;
Data() {}
~Data() {}
public:
static Data& instance() ;
// ...
} ;
Data* Data:: ourInstance = &instance() ;
Data&
Data::instance()
{
if ( ourInstance == NULL ) {
ourInstance = new Data ;
}
return *ourInstance ;
}
This solves the threading issues (for the most part), and
avoids any order of destruction issues, by not destructing
the object.
FWIW, this is how to break it using threads:
http://groups.google.com/group/comp.lang.c++/msg/769cda6552764337
Yes. If you start a thread which uses it from the constructor,
you will have problems. That's what the "(for the most part)"
refers to. (In my actual library, this restriction is
documented.)
In practice, I've never found this to be an issue. Nor have I
found Keith Duggar's point, that the object will always be
constructed, even if it is never used, and issue---just the
opposite, in most of my applications, start-up time is more or
less free, but I have time constraints when responding to a
request, so anything that can be moved out into the program
initialization phase is good. Still, it's a point that should
be documented (and that IIRC, I forgot to document in my generic
implementation).
--
James Kanze