Re: Custom constructor and the Meyers Singleton
On Feb 23, 1:26 pm, irotas <goo...@irotas.net> wrote:
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.
A better solution might be to not use the singleton. It's very
controversial and you can't possibly know that there won't at some
point be a need for having two of them. You might argue "there are
times when a singleton is obvious! You wouldn't have two kernals,
would you?" And I might respond "might future OSs possibly have two
kernals? You can't know."
But, as for your configure solution, I do have a work-a-round. Globals
are always initialized before int main, although not always before
functions that use them. I could declare a global int and define it as
the return of configure().
Singleton::arg1 = 6;
int hack = configure();
I called that hack because this really is a hack, it's obvious, and is
certainly not a preferable we to handle this. You could have configure
just set default values, or you could, in another file, set another
global to configure (or any other function that'll do the same job)
and it'd be done, but if I was reading your documentation and I got to
that page, I'd say "You want me to do what now?"
You could force the user to define a SINGLTON_MACRO before #including
your header. This way, the internal modification done to the class is
done by the compiler. But, again, I think this is a hack and not a
great way to interface code. But, perhaps it'd be better if you had
the user define a macro per argument. Still not great, though.
Really, I'd just encourage you not to use the singleton pattern. I'd
use a plain global initialized by global_init()--or some such
function--or main itself. I've used that global trick before, but only
to ensure run-time conditions and no one outside that file ever knew
Then again, maybe by the time my post is posted, you'll have ten other
posts giving good solutions and I'll get replies disputing my claims.
We'll see. Good luck!
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]