Re: Assign Reference to another Referance
On 26 Set, 00:02, cpisz <cp...@austin.rr.com> 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.
I'm not so sure, but I think that global objects get created first of
anything else, while static objects get created the first time that
the function they appear in gets called. If you have "void f()
{ static Foo foo(); }" and you don't call f(), then foo shouldn't be
created at all, I think.
- main returns
Yes
- foo starts being destroyed
- a Singleton gets created
Maybe, maybe not. The order of deinitialization is also undefined.
Wait, "new Singleton" gets executed only the first time that Instance
() gets called, and Instance() gets called for the first time within
the Foo dtor (I might have worded it badly, with "starts being
destroyed" I meant "the dtor starts executing"). If I got it right,
the order of the above should be well defined.
- x gets created
- x gets destroyed
This will happen only when foo gets destroyed, when that happens isn't
defined
At this point I think I should throw away my book. I've been taught
that local, non-static variables get created and destructed at every
function call, and x is a local, non-static variable of DoStuff().
- 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.
Taking for granted that I haven't completely misunderstood the
construction-destruction orders, the first object to be created should
be the last to be destroyed (that's the logic I followed while writing
the sequence above).
I think I need some of those +30y experienced people to throw some
light on this - I'm 30yo, some 60yo around?
[ I would address the paragraphs of yours that I snipped, but I
wouldn't feel on firm ground, sorry, I prefer to stop here ]
In impatient waiting,
Francesco
--
Francesco S. Carta, hobbyist
http://fscode.altervista.org