Controlling the initialization order of global objects in Visual C ++

zhaozj2021-02-16  142

In C , the initialization order of the global object in the same translation unit (.cpp) is the first-defined object first initialization (after also analyzing), but the C standard does not specify the initialization order of global objects between different translation units. . According to this analysis, the following code may work, or it may not work (COUT is a global object of C for output, and our own object is located in different translations):

Class a {a () {cout << "A:: A ()";} ~ a () {cout << "A :: ~ a ()";}};

A a a;

OK, you will say that this code is absolutely running correctly, that is, COUT is always initialized than our object, and later. This is reason - although the C standard does not clearly stipulates, each C compiler implements the control of the initialization of the global object, otherwise, the C library cannot work in the expected manner (if There may not be allowed to use COUT in the global object constructor to be mad.).

Visual C provides a compiling instruction such as #pragma init_seg to control the initialization order of objects in a translation unit. Open the CRT source code file cout.cpp with Visual C , you will find the following statement:

#pragma Warning (Disable: 4074) #pragma init_seg (Compiler)

_CRTIMP2 OSTREAM COUT (& fout);

By using #pragma init_seg (compiler), all objects in the COUT.CPP file are placed in the COMPILER initialization group, and the objects in this group are always initialized and finalized. Of course, this group is reserved for Microsoft C / C runtime, we should not use it. In our own code, if you want some objects to initialize other objects, we can use the #pragma init_seg (lib) instruction, the object placed in the lib group is always later than the object of the Compiler group, but must first prior to other objects . #pragma init_seg The instruction There are other advanced usage let you make more detailed control.

(Note: Compiling instructions do not belong to standard C features)

转载请注明原文地址:https://www.9cbs.com/read-8169.html

New Post(0)