[Link to this article]
Http://www.cnblogs.com/hellogiser/p/global-local-static-object.html
[Analysis]
1. Life Cycle Problem: static variables are stored and allocated in a fixed memory area. The life cycle of the variables ends until the end of the program running. Common variables: local variables and global variables are stored and allocated in different places. Local variables are stored and allocated in the stack. The Life Cycle of variables ends with the exit of the function; global variables are stored and allocated in the static storage area (the same as static variables ).
2. visibility: static variables in a class are invisible outside the class; static variables in the function are invisible outside the function; static variables outside the function are only visible to the current compilation unit.
3. Initialization problem: the Global static variable is initialized before the main function is run, and the local static variable is initialized when the function where it is called for the first time. For internal types, the character type is initialized to 0 characters with an ASCII value, and the other types are initialized to 0. The user-defined type must be initialized by the constructor.
Note: If a function containing a local static object is not called, the constructor of this object will not be called.
4. destructor calls of static objects: they are called only when the program exits from main () or when the standard C library function exit () is called. When abort () is called to exit the program, the destructor of the static object will not be called. Static objects are destroyed in the reverse order of initialization.
[Code]
C ++ code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
|
/* Version: 1.0 Author: hellogiser Blog: http://www.cnblogs.com/hellogiser Date: 2014/9/20 */
# Include "stdafx. H" # Include "iostream" Using namespace STD;
Class myclass { Char C; Public: Myclass (char CC): C (cc) { Cout <"myclass: myclass () for" <C <Endl; } ~ Myclass () { Cout <"myclass ::~ Myclass () for "<C <Endl; } };
Static myclass A ('A'); // Global static Void F () { Static myclass B ('B'); // local static }
Void g () { Static myclass C ('C'); // local static }
Int main () { Cout <"Inside main ()" <Endl; F (); Static float F; // local static initialized with 0 Static int I; // local static initialized with 0 Cout <"float F:" <F <Endl; Cout <"int I:" <I <Endl; Cout <"leaving main ()" <Endl;
Return 0; } /* Myclass: myclass () for Inside main () Myclass: myclass () for B Float F: 0 Int I: 0 Leaving main () Myclass ::~ Myclass () for B Myclass ::~ Myclass () for */ |
[Reference]
Http://www.cnblogs.com/liujiangyi/archive/2012/08/13/2635840.html
Global-local-static-Object