Re: Custom constructor and the Meyers Singleton
After thinking about this for a while, one wild idea came to mind.
What if we create a second singleton, called SingletonConfigurator,
that the application can use to set the parameters needed for
Singleton's constructor. SingletonConfigurator could even set default
value where appropriate, so that the user doesn't even need to know
that the SingletonConfigurator exists unless they really need it.
Then, 'Singleton::instance()' could get the configuration parameters
from SingletonConfigurator and pass them on to the Singleton
constructor.
Here's the updated (working!) code:
/////////////////////////////////////////////////////////////////////////////
#include <iostream>
using std::cout;
using std::endl;
class SingletonConfigurator
{
public:
static
SingletonConfigurator&
instance()
{
static SingletonConfigurator c;
return c;
}
int mNum;
private:
SingletonConfigurator()
: mNum(0)
{
}
};
class Singleton
{
public:
static
Singleton&
instance()
{
static Singleton s(SingletonConfigurator::instance().mNum);
return s;
}
int
num() const
{
return mNum;
}
private:
Singleton(int num)
: mNum(num)
{
}
const int mNum;
};
void
func()
{
Singleton& s = Singleton::instance();
cout << "Singleton: " << s.num() << endl;
}
int
main(int argc, char** argv)
{
SingletonConfigurator& c = SingletonConfigurator::instance();
c.mNum = 5;
func();
return 0;
}
/////////////////////////////////////////////////////////////////////////////
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]