Re: Singleton Pattern
On Apr 19, 3:07 pm, Keshav <gupta.kes...@gmail.com> wrote:
I would like to know whetehr this is the right way to
implement thread safe singleton.
There is no "right" way. There are a number of different
solutions, appropriate in different cases. However...
Generally we do locking and all at Instance method, Can we get
rid of these problems if we create instance while defining
pInstance variable.
Locking each access is the "most correct" method.
Would it create any problem?
Only if you start a thread from a static constructor which uses
the singleton. I'd consider that bad practice, however, and in
practice, I use this solution most of the time.
//CODE SNIPPET
class Sing
{
public:
static Sing* Instance();
protected:
Sing(){}
~Sing(){}
private:
Sing(const Sing&);
Sing& operator= (const Sing&);
static Sing* pinstance;
};
Sing* Sing::pinstance = Instance(); // Please NOTE THIS.
pInstance is initialized at definition.
Actually, it's initialized twice. First, it's zero initialized
before any actual code runs, then it is initialized with the
actual object during dynamic initialization.
Sing* Sing::Instance ()
{
if (pinstance == 0)
pinstance = new Sing;
return pinstance;
}
As I said, this is what I do most of the time. It has two
possible disadvantages: if you start a thread from the
constructor of another static object, you risk a race condition,
and if you never need the instance, you'll construct it anyway.
If neither of these are a consideration in your code, it's
probably the simplest solution.
--
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