Re: singleton - dead reference
Hoobert wrote:
That's placement new.
It calls the constructor. Of course it is only allowed to do that
after the destuctor has been called, which is done in KillPhoenix.
Basically, it's a singleton you can kill and resurrect.
I know what is "placement new". I don't understand why I have to use
it at this place. Singleton destructor sets pointer to 0. Then Create
method assigns to this pointer address of static instance of Singleton
so pointer becomes valid. I think I don't need calling placement new.
I removed placement new call and simulated dead reference behavior. I
ran program under valgrind to pick memory access issues and everything
worked fine. Maybe it's implementation issue that it worked in my
case. Anyway I'd like to know what happens here.
The placement new invocation is there to make sure you are working with
a valid object, instead of a bag of bytes.
If your testing did not show the use of placement new, your test was not
good enough.
Try this test instead, both with RESURRECT defined and undefined to see
the difference:
#include <iostream>
using namespace std;
#define RESURRECT
class Singleton {
public:
static Singleton& Instance() {
if (!pInstance_) {
if (destroyed_) OnDeadReference();
else Create();
}
return *pInstance_;
}
/* BvIN Added: */
void print() {
if (p) cout << p << endl;
else cout << "Trying to print a non-object" << endl;
}
private:
static void Create() {
static Singleton instance;
pInstance_=&instance;
}
static void OnDeadReference() {
Create();
#ifdef RESURRECT
new(pInstance_) Singleton;
#endif
atexit(KillPhoenix);
destroyed_=false;
}
static void KillPhoenix() {
pInstance_->~Singleton();
}
virtual ~Singleton() {
pInstance_=0;
destroyed_=true;
/* BvIN: Added */
delete[] p;
p = 0;
cout << "Singleton destructed" << endl;
}
static Singleton *pInstance_;
static bool destroyed_;
/* BvIN: Added */
Singleton() : P(new char[sizeof("Valid object")]) {
strcpy(p, "Valid object");
cout << "Singleton constructed" << endl;
}
char* p;
};
struct Test {
void foo() {
cout << "Enter Test::foo()" << endl;
Singleton::Instance().print();
cout << "Leave Test::foo()" << endl;
}
~Test() {
cout << "Enter Test::~Test()" << endl;
Singleton::Instance().print();
cout << "Leave Test::~Test()" << endl;
}
} TestGlobal;
int main() {
cout << "Enter main()" << endl;
TestGlobal.foo();
cout << "Leave main()" << endl;
}
/* Expected output, for a properly functioning program:
Enter main()
Enter Test::foo()
Singleton constructed
Valid object
Leave Test::foo()
Leave main()
Singleton destructed
Enter Test::~Test()
Singleton constructed
Valid object
Leave Test::~Test()
Singleton destructed
*/
Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://c-faq.com/
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]