Given this code:
#include <iostream>
using namespace std;
class Foo {
public:
Foo () { c = 'a'; cout << "Foo()" << endl; }
Foo (char ch) { c = ch; cout << "Foo(char)" << endl; }
~Foo () { cout << "~Foo()" << endl; }
private:
char c;
};
class Bar : public Foo {
public:
Bar () { cout << "Bar()" << endl; }
Bar (char ch) : Foo(ch) { cout << "Bar(char)" << endl; }
~Bar () { cout << "~Bar()" << endl; }
};
Foo f1; static Bar b1;
int main()
{
Bar b2;
{
static Foo f2('c');
Foo f3;
Bar b3 ('d');
}
return 0;
}
(You can just paste this directly into a compiler)
The first part of my expected sample output is correct:
Foo()
Foo()
Bar()
Foo()
Bar()
Foo(char)
Foo()
Foo(char)
Bar(char)
~Bar()
~Foo
~Foo()
~Bar()
~Foo()
~Foo()
But I get the destructor output of the two static objects static Bar b1; and static Foo f2('c'); wrong.
The correct answer for the last part is:
~Bar()
~Foo()
~Foo()
I get:
~Foo()
~Bar()
~Foo()
This is my reasoning:
I understand that all local objects are destructed before static objects. Of the two remaining static objects static Bar b1; and static Foo f2('c');, static Foo f2('c'); appears last, so it is destructed first, because destructors are called in the reverse order of their creation.
But static Foo f2('c'); isn’t destructed first, static Bar b1; is. Why?
Modified you program :
Which generates the following output in g++ 4.5.2:
You see that the last destructed one is the non-static global variable
Foo f1.EDIT:
As the others mentioned, the initialization order of variables with static storage duration is unspecific if the variables are from different translation units, but they can be defined when they are in the same translation unit.
Initialization by constructor calls (as in this examples) are called
dynamic initialization, andThe initialization of local static variables is specified as
And as the destruction of variables with static storage duration should be in the reverse order of their construction, so the order of construction and destruction of the variables with types
FooandBarin this example is in fact defined.Again, when you have multiple translation, you’d better not to rely on the order of initialization.