Re: singleton - dead reference
On Nov 14, 9:44 am, Hoobert <michal...@yahoo.pl> wrote:
Hello,
While reading "Implementing Singletons" in "Modern C++ Design" by A.
Alexandrescu I bumped into example:
//-----------------------------------------------
class Singleton {
public:
static Singleton& Instance() {
if (!pInstance_) {
if (destroyed_) OnDeadReference();
else Create();
}
return *pInstance_;
}
private:
static void Create() {
static Singleton instance;
pInstance_=&instance;
}
static void OnDeadReference() {
Create();
new(pInstance_) Singleton;
atexit(KillPhoenix);
destroyed_=false;
}
static void KillPhoenix() {
pInstance_->~Singleton();
}
virtual ~Singleton() {
pInstance_=0;
destroyed_=true;
}
static Singleton *pInstance_;
static bool destroyed_;};
//-----------------------------------------------
which addresses problem of dead references due to order of static
objects' destruction. I don't get the OnDeadReference function:
why there is "new(pInstance_) Singleton;" ?
Destructor only resets pointer so when we call Create it again points to
Singleton.
Regards
Destructor is called when "static Singleton instance" is destroyed, so
OnDeadReference needs to create it again. This code assumes memory for
static object is still there, which I don't think is guaranteed by the
standard.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]