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 .