Trolltech Home | Qt-interest Home | Recent Threads | All Threads | Author | Date
All threads index page 4

Qt-interest Archive, May 2003
Explanation of Singleton (was: Can static classes emit signals?)


Message 1 in thread

Von:	Florian Lindner [mailto:mailinglists@xgm.de]
> Hey,
> would you explain what a singleton is?

A singleton is a class which guarantees that there is no more than one instance of it (while there might be no instance also). "Singleton" is the name of the design pattern described by Gamma et. al.

An example implementation might look like

singleton.h:

  class SingletonExample
  {
    public:

      static SingletonExample *instance ()
      {
          if (m_instance == 0)
              m_instance = new SingletonExample ();

          return (m_instance);
      }

      ~SingletonExample ()
      {
          m_instance = 0;
      }

      // other (non-static) methods

    private:

      SingletonExample ()
      { }

      static SingletonExample *m_instance;
  };

singleton.cpp:

  #include "singleton.h"

  SingletonExample *SingletonExample::m_instance = 0;

Any errors in the above example are intended as part of a reading comprehension test ;-)


Message 2 in thread

On May 9, 2003 11:53 am, Rainer Wiesenfarth wrote:
>
> A singleton is a class which guarantees that there is no more than one
> instance of it (while there might be no instance also). "Singleton" is the
> name of the design pattern described by Gamma et. al.
>
> An example implementation might look like
>
> singleton.h:
>
>   class SingletonExample
>   {
>     public:
>
>       static SingletonExample *instance ()
>       {
>           if (m_instance == 0)
>               m_instance = new SingletonExample ();
>
>           return (m_instance);
>       }
>
>       ~SingletonExample ()
>       {
>           m_instance = 0;
>       }
>
>       // other (non-static) methods
>
>     private:
>
>       SingletonExample ()
>       { }
>
>       static SingletonExample *m_instance;
>   };
>
> singleton.cpp:
>
>   #include "singleton.h"
>
>   SingletonExample *SingletonExample::m_instance = 0;
>
> Any errors in the above example are intended as part of a reading
> comprehension test ;-)

This is a good example and shows, in code, what a singleton is.  Note, though, 
that it is not thread-safe.  Furthermore, it leaks memory in the destructor 
though, due to the nature of singletons, this is not likely to be a 
significant problem.

-- 
 [ signature omitted ] 

Message 3 in thread

From: Chris Thompson [mailto:chris@hypocrite.org]
> This is a good example and shows, in code, what a singleton
> is.  Note, though, that it is not thread-safe.

Agreed. To make it thread save, add a static QMutex and use it to protect the method bodies.

> Furthermore, it leaks memory in the destructor though, (...)

Where? I do not see it. Could you give me a hint?