From:http://blog.csdn.net/classfactory/archive/2004/08/07/68202.aspx
In C + +, the initialization order of global objects in the same translation unit (. cpp file) is first initialized (and post-destructor), but the C + + standard does not specify the sequence of initialization of global objects between different translation units. According to this analysis, the following code may or may not work (cout is a global object that C + + uses for output, and our own objects are located in different translation units):
Class A {
A () {
cout << "a::a ()";
}
~a () {
cout << "A::~a ()";
}
};
A;
OK, you would say that this code is absolutely correct, which means that cout is always initialized and post-destructor than our object. This is for a reason-although the C + + standard is not explicitly defined, each C + + compiler has implemented a similar approach to control the initialization of the global object, otherwise the C + + library will not work as expected (if you are not allowed to use cout in a global object constructor) Maybe a lot of programmers will go insane).
Visual C + + provides a compilation directive #pragma init_seg that controls the order in which objects in a translation unit are initialized. Open Visual C + + with the CRT source code file Cout.cpp, you will find the following statement:
#pragma warning (disable:4074)
#pragma init_seg (compiler)
_CRTIMP2 ostream cout (&fout);
By using the instruction #pragma init_seg (compiler), all objects in the Cout.cpp file are placed in the compiler initialization group, and the objects in the group are always initialized and finally refactored. Of course, this group is reserved for use by the Microsoft C + + runtime, and we should not use it. In our own code, if you want some objects to be initialized before other objects, we can use the #pragma init_seg (lib) directive, and the objects placed in the Lib group are always later initialized than the objects in the compiler group, but before other objects. There are other advanced uses of the #pragma init_seg directive to give you more granular control.
(Note: Compilation directives are not part of the standard C + + features)
[Baidu Space] [Go] control the initialization order of global objects in Visual C + +