Re: newbie question on singleton class
On May 13, 2:11 am, Gianni Mariani <gi3nos...@mariani.ws> wrote:
On May 12, 11:53 pm, pauldepst...@att.net wrote:
I liked this article by Danny Kalev on the singleton design
class:http://gethelp.devx.com/techtips/cpp_pro/10min/10min0200.asp
However I was confused by this:
QUOTE BEGINS HERE
The class's implementation looks like this:
Singleton* Singleton::pinstance = 0;// initialize pointer
Singleton* Singleton::Instance ()
{
if (pinstance == 0) // is it the first call?
{
pinstance = new Singleton; // create sole instance
}
return pinstance; // address of sole instance
}
A much easier way to write this is:
Singleton* Singleton::Instance ()
{
static Singleton* pinstance = new Singleton;
return pinstance; // address of sole instance
}
This will also generate thread safe code on some compilers.
...
So it is claimed. In fact, I only know of one compiler that
even tries, and it fails on my most important target (Solaris on
Sparc).
In practice, what I usually do is to leave the instance variable
outside of the function (more often in an anonymous namespace
than as a static member), and write something like:
Singleton* ourInstance = Singleton::instance() ;
This ensures (in practice, anyway) that the Singleton::instance
function is called before entering main, and thus before I've
created any threads. And once the pointer is non-null, it is
never modified, so (at least according to Posix), there is no
longer any need to protect accesses. (Note that this code is a
little tricky, since it counts on zero initialization.)
So I would have thought that Singleton* Singleton::pinstance = 0;
violates private access.
The initialization expression is in the scope of the class.
And doesn't access any private variables anyway:-).
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34