Re: Singleton Pattern
On Apr 19, 9:07 am, Keshav <gupta.kes...@gmail.com> wrote:
HI,
I would like to know whetehr this is the right way to implement
thread safe singleton.
Generally we do locking and all at Instance method, Can we get rid of
these problems if we create instance while defining pInstance
variable.
Would it create any problem?
//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.
Sing* Sing::Instance ()
{
if (pinstance == 0)
pinstance = new Sing;
return pinstance;
}
Thanks
K2
I assume your code post is actually the .h and the .cpp file.
You could initialize pinstance as you did if you make pinstance a non-
pointer.
But then you need to consider two issues:
1. You are creating this object even if it is never used.
2. If another singleton uses this singleton, you run into order of
initialization
issues. There is no guarentee that the singleton that is needed is
created before
the one that needs it if there are defined in separate compilation
units.
By creating the objects on demand, you don't have these issues.
HTH