Custom constructor and the Meyers Singleton
This question is with respect to the so-called "Meyers Singleton"
described in various places on the web. Here's one simple description:
http://www.devarticles.com/c/a/Cplusplus/C-plus-plus-In-Theory-The-Singleton-Pattern-Part-I/4/
I've used this pattern many times with great success. However, one
thing that is bothering me now is that the pattern relies on no-
argument construction of the singleton object. That's always been fine
for me before, but now I need my singleton constructor to take an
argument.
Consider the following sample code:
/////////////////////////////////////////////////////////////////////////////
#include <iostream>
using std::cout;
using std::endl;
class Singleton
{
public:
static
Singleton&
instance()
{
static Singleton s; // error, Singleton constructor requires an
argument
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)
{
func();
return 0;
}
/////////////////////////////////////////////////////////////////////////////
I really don't want to add an argument to the 'instance()' method to
pass on to the constructor, because that would require all callers to
provide that argument.
I've considered adding a special 'configure()' method that the
application calls once to initialize the singleton, and have the
'instance()' method call 'configure()' internally. The problem is that
I really have no way of knowing if the application called 'configure
()' explicitly multiple times.
Has anyone ran into this problem before? Any suggestions on how to
redesign the singleton to allow for a custom constructor and at least
detecting multiple initialization attempts?
Thanks,
Adam
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]