successfully constructed. Because B::B completes after A::A, that means ~B
will be called before ~A.
"Igor Tandetnik" <itandetnik@mvps.org> wrote in message
news:OWR%23$YbVJHA.3912@TK2MSFTNGP06.phx.gbl...
I'm talking about function-static objects, like this:
Singleton* getInstance() {
static Singleton instance;
return &instance;
}
These get constructed the first time the function is called.
Exactly. That's the whole problem in this case. Because a global which
uses this object will invoke "instance"s constructor after it's own
constructor has been pushed onto the destruct stack, meaning that
"instance" will (or "could" to be more accurate) die first (ie. before the
global).
I say "could" because I was just going to demonstrate it to you with a
small program. But when I try the experiment in a single file it works
(which pisses me off because I'd like to prove what I know actually
happens!). I mean the assert is quite explicit, exactly what you get when
trying to access an already-destroyed STL container...
But this stupid program:
struct A
{
A() {puts("A::A");}
~A() {puts("A::~A");}
};
A* func()
{
static A a;
return &a;
}
struct B
{
B() {puts("B::B");func();}
~B() {puts("B::~B");}
};
B b;
int main(int,...)
{
return 0;
}
Lets A live longer than B. Why? I have no clue. The order is this:
B::B
A::A
B::~B
A::~A
ie. not FILO. For some reason the compiler gets it right and doesn't
destroy in reverse order...
- Alan Carre