Fiasco Static Initialization - as intended

Just for fun, I studied the dynamic initialization order of static objects. In the file name th, I put

struct T {
   static std::vector<std::string> me;
   static int add(std::string s) { me.push_back(s); return me.size(); }
};

(Plus you need headers for the vector and the string). "std :: vector T :: me" is located in t.cpp. The main.cpp file prints the values ​​in T :: me:

#include "t.h"
#include <iostream>
using namespace std;

int main()
{
    T::me.push_back("main");
    cout << "T::me.size()=" << T::me.size() << endl;
    for (unsigned i = 0; i<T::me.size(); ++i) {
        cout << i << "-" << T::me[i] << endl;
    }
    return 0;
}

next, I create "a.cpp" and put the following into it:

#include "t.h"

int a = T::add("a");

Do the same for the b.cpp and c.cpp files using "b" and "c" if necessary. Compile with g ++ * .cpp, then run. /a.out. The order of static initialization from compilation unit to compilation unit is not specified. In my case, it is sequentially in reverse alphabetical order. I got: 3 - c 2 - b 1 - a 0 - main

No problem so far.

u.cpp a.cpp, "u". /, "u" .

, u? a, b, c, main:

#include "t.h"
#include <iostream>
using namespace std;

extern int u;

int main()
{
    cout << "u=" << u << endl;
    T::me.push_back("main");
    cout << "T::me.size()=" << T::me.size() << endl;
    for (unsigned i = 0; i<T::me.size(); ++i) {
        cout << i << "-" << T::me[i] << endl;
    }
    return 0;
}

"u = 2", "u" . u , T:: me , "u"? , , , u t .

+3
2

. , . T:: me , ++. . , . -, - u.

+3

, compilation :

g++ -o m a.cpp u.cpp t.cpp main.cpp

a=2
u=1
T::me.size()=3
0-u
1-a
2-main

g++ -o m main.cpp t.cpp a.cpp u.cpp

a=2
u=1
T::me.size()=1
0-main

a.cpp u.cpp a=1 u=2.

!

+1

All Articles