Re: C++ singleton pattern question

From: Noah Roberts (nroberts_at_stmartin.edu)
Date: 02/22/05


Date: 22 Feb 2005 09:54:41 -0800


ferdinand.stefanus@gmail.com wrote:
> Hi
>
> Could someone tell me what's the difference between these two
singleton
> implementations:

You don't control initialization in the first case. In the second case
you do.

I usually do something like this:

class Singleton
{
  Singleton *instance;
  Singleton() {}
public:
  void function1() { blah; }
  static void function1 { if (instance == NULL) instance = new
Singleton();
                          instance->function1(); }
};

in Singleton.cpp:
Singleton *Singleton::instance = NULL;

I don't know off hand if C++ allows static and non-static functions to
have same signature...you may have naming issues w/ regard to above.
It is the basic structure that is important. You will probably want a
const accessor also.



Relevant Pages

  • Re: Writing Singleton Classes
    ... cppaddict wrote: ... The first implementation needs a slight change to be thread-safe: ... There are a dozen or so Singleton articles on CodeProject; ... A review and analysis of existing C++ implementations ...
    (comp.lang.cpp)
  • Singleton Implementation Issue
    ... Unless I'm misunderstanding the pattern and it's various implementations, ... Singleton effectively makes the constructor unavailable to clients. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: question: static objects in LIB
    ... > lib file seems to override whatever singleton we implement. ... The function localtimeholds its own buffer of struct tm, ... From the Alexandrescu's book show some implementations of Singleton. ...
    (microsoft.public.vc.language)