[prev in list] [next in list] [prev in thread] [next in thread]
List: amarok-devel
Subject: Re: RFC: singletons and memory management
From: "Soren Harward" <stharward () gmail ! com>
Date: 2008-09-11 2:52:15
Message-ID: 640748050809101952j2a8b9066pcadb63aef9c109c1 () mail ! gmail ! com
[Download RAW message or body]
On Wed, Sep 10, 2008 at 6:45 PM, Leo Franchi <lfranchi@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
_______________________________________________
Amarok-devel mailing list
Amarok-devel@kde.org
https://mail.kde.org/mailman/listinfo/amarok-devel
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic