RFC: singletons and memory management

Soren Harward stharward at gmail.com
Thu Sep 11 04:52:15 CEST 2008


On Wed, Sep 10, 2008 at 6:45 PM, Leo Franchi <lfranchi at kde.org> wrote:
> I don't really see it being an issue. If it is called when it doesn't
> exist b/c it has been deleted, it is created. But that should never
> happen---if we delete it, it should be the last time it is accessed.
>
> So whats wrong?

Take the following code, which is the standard Singleton structure
according to Design Patterns:

class Singleton {
  public:
    Singleton* instance();
    ~Singleton();
    ...
  private:
    Singleton* s_instance;
    Singleton();
    ...
}

Singleton* Singleton::s_instance = 0;

Singleton* Singleton::instance() {
  if (!s_instance) {
    s_instance = new Singleton();
  }
  return s_instance;
}

What happens is that if you call "delete Singleton::instance()", then
the object pointed to by s_instance is freed, but s_instance is never
reset to zero.  So the next time you call Singleton::instance(), it
will hand back the memory location where the object used to be, and
you'll get a segfault.  You need to call a static Singleton::destroy()
member to set the s_instance pointer to zero after the object is
deleted, so that the next time Singleton::instance() gets called, it
will create a new object.  You could also use a "smart" pointer like
auto_ptr or QPointer that automatically set to zero when they're
deleted, but I personally prefer the static destroy() method.  At any
rate, the Singleton classes in Amarok should be a little smarter about
their memory management.

-- 
Soren Harward


More information about the Amarok-devel mailing list