Transferred from: http://www.cnblogs.com/zhenjing/archive/2010/10/15/1852116.html
For C language Global and static variables, regardless of whether it is initialized, its memory space is global, if initialized, then initialization occurs before any code execution, the compilation period is initialized. Because the built-in variable does not need the resource release operation, only needs to reclaim the memory space, therefore the global memory space is reclaimed together after the program end, there is no variable dependency problem, no code will be executed again!
C + + introduced the object, which gives the management of global variables a new hassle. The C + + object must have a constructor generated and eventually perform a destructor operation. Since construction and destruction are not as simple as allocating memory, it can be quite complex, so when do the construction and destruction of global or static objects (C + +) be performed?
1#include <iostream>2#include <string>3 using namespacestd;4 5 classVar {6 Public :7Var (Const string&str)8 {9Name =str;Tencout<<"Initialize:"<<name<<Endl; One } A -~Var () {} - the voidPrint () - { -cout<<"Print:"<<name<<Endl; - } + Private: - stringname; + }; A atVar VAR1 ("Global var1"); - StaticVar Var2 ("Static Var2"); - - voidFunc () - { - StaticVar Var3 ("Func Static Var3"); in Var3. Print (); - } to + intMainintargcChar**argv) - { thecout<<"Main start ..."<<Endl; * VAR1. Print (); $ var2.print ();Panax Notoginseng Func (); - thecout<<"Main End ..."<<Endl; +System"Pause"); A return 0; the } + - //Output $ //Initialize: Global var1 $ //Initialize: Static var2 - //Main start ... - //Print:global var1 the //print:static var2 - //initialization: Func static VAR3Wuyi //print:func Static Var3 the //Main End ...
The result of the VS2012 compilation is that both the global variables and the static variables of the file fields are initialized before main starts, and only local static variables within the function are initialized at the first use.
C + + global and static variable initialization