From: Kris Prad on
On Dec 15, 12:29 am, Francis Glassborow
<francis.glassbo...(a)btinternet.com> wrote:
> Kris Prad wrote:
> > I want to setup a singleton, without 'static' initialization. My
> > motive is to control the life time of the Singleton, bounded by its
> > scope, something I cannot do with the statics.
>
> > Not this way. This uses static:
>
> > Single* Get()
> > {
> > Static Single s; // do not want static
> > Return &s;
> > }
>
> > Instead, I am doing this (please ignore thread safety issues)
> > Single* g_Single = NULL; // global singleton ptr
> > struct Single
> > {
>
> > Single()
> > {
> > if (!g_Single)
> > {
> > g_Single = this;
> > }
> > else
> > {
> > throw string("Single is a singleton");
> > }
> > }
> > ~Single()
> > {
> > g_Single = NULL;
> > }
> > };
>
> > Is this ugly or acceptable?
>
> > Kris
>
> What is wrong with this:
>
> class Single {
> public:
> Single(){
> if(exists) throw("You can only have one object of type Single");
> exists = true;
> // do rest
> }
> ~Single() { exists = false }
> // rest of interface
> private:
> static bool exists;
> // rest of private interface etc.
>
> };
>
> bool Single::exists(false);
>
> The trouble with your use of a global variable is that it could be
> accidentally modified and the compiler will not be able to help you.

True.

I have something similar in mind:

struct Single
{

Single()
{
if (!m_single)
{
m_single = this;
}
else
{
throw ("Single is a singleton");
}
}

~Single()
{
m_single = NULL;
}

static Single* Get() { return m_single; } // can retrun NULL
private:
static Single* m_single; // private singleton ptr

};

Single* Single::m_Single = NULL;


Kris

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]