Re: Assign Reference to another Referance
cpisz wrote:
class Singleton
{
public:
static Singleton & Instance()
{
if( !m_instance )
{
m_instance = new Singleton();
}
return *m_instance;
}
static void DoStuff()
{
int x = 1 + 1;
}
private:
static Singleton * m_instance;
};
Singleton * Singleton::m_instance = 0;
class Foo
{
public:
Foo(){}
~Foo()
{
Singleton::Instance().DoStuff();
}
};
int main()
{
static Foo foo;
return 0; // Undefined behavior after this line, when program
cleanup occurs!
}
static de-initialization fiasco.
Sorry for dropping in, maybe I have not the right grip on the subject
but I want to show what I understand about your program, and take the
chance to learn something new.
If I get it right, this is the sequence:
--- start of execution
- m_instance gets created
- foo gets created
The order of initialization is not defined. foo might get created
before m_instance or vica versa.
Wrong (the last sentence). m_instance is initialized to zero before
main, but foo is constructed inside of main.
- main returns
Yes
- foo starts being destroyed
- a Singleton gets created
Maybe, maybe not. The order of deinitialization is also undefined.
It is undefined, but m_instance and the object it points to are never
destroyed. Their memory are release after the end of the program, when
there's no more program code running.
- x gets created
- x gets destroyed
This will happen only when foo gets destroyed, when that happens isn't
defined
- foo finishes its destruction
yes
- m_instance gets destroyed
Whether or not this occurs before foo is destroyed is undefined. That
is the problem and is the de-initialization fiasco.
m_instance is never destroyed. The pointee is never destroyed, too. Only
its memory will be released.
The problem is there are two variables in static or global space. The
destruction of one relies on the other existing.
There's a pointer that has no destructor, so no code is running for its
destruction.
I don't see any race condition in this example code.
--
Thomas