1. What is static?
static is a very commonly used modifier in C/C++. It is used to control the storage mode and visibility of variables.
1.1 Introduction of static
We know that for variables defined inside a function, when the program executes to their definition, the compiler allocates space for them on the stack. The space allocated on the stack by the function will be released when the function finishes executing. This creates a problem: if you want to save the value of this variable in the function until the next call, how can it be achieved? The easiest method to think of is to define it as a global variable, but defining a global variable has many disadvantages. The most obvious disadvantage is that it destroys the access scope of the variable (making the variable defined in this function not only controlled by this function). The static keyword can solve this problem well.
In addition, in C++, when a data object needs to serve the entire class rather than a specific object, and at the same time strives not to break the encapsulation of the class, that is, when the member is required to be hidden inside the class and invisible to the outside, it can be defined as static data.
1.2 Storage of static data
Global (static) storage area: It is divided into the DATA segment and the BSS segment. The DATA segment (global initialized area) stores initialized global variables and static variables; the BSS segment (global uninitialized area) stores uninitialized global variables and static variables. They are automatically released when the program ends. Among them, the BSS segment will be automatically cleared to 0 by the system before program execution, so uninitialized global variables and static variables are already 0 before program execution. Variables stored in the static data area complete initialization when the program first starts running, and this is the only initialization.
Internal implementation mechanism of static in C++: Static data members must exist as soon as the program starts running. Because functions are called during program execution, static data members cannot be allocated space and initialized inside any function.
In this way, there are three possible places for its space allocation: first, the header file as the external interface of the class, where the class declaration is located; second, the internal implementation of the class definition, where the member function definitions of the class are located; third, the global data declaration and definition before the main() function of the application.
Static data members need to actually allocate space, so they cannot be defined in the class declaration (only data members can be declared). The class declaration only declares the "size and specifications" of a class and does not perform actual memory allocation, so writing a definition in the class declaration is wrong. It also cannot be defined outside the class declaration in a header file, because that would cause repeated definitions of it in multiple source files that use the class.
static is introduced to tell the compiler to store variables in the program's static storage area rather than on the stack. Static data members are initialized in the order in which they are defined. Note that when static members are nested, it is necessary to ensure that the nested members have already been initialized. The order of destruction is the reverse of the order of initialization.
Advantages:It can save memory because it is shared by all objects. Therefore, for multiple objects, static data members are stored in one place and shared by all objects. The value of a static data member is the same for every object, but its value can be updated. As long as the value of the static data member is updated once, all objects are guaranteed to access the same updated value, which can improve time efficiency.
2. The role of static in C/C++
2.1 In general
- (1) When modifying variables, the static local variable modified by static is initialized only once, and it extends the lifetime of the local variable, which is not released until the program finishes running.
- (2) When static modifies a global variable, this global variable can only be accessed in the current file and cannot be accessed in other files, even with an extern external declaration.
- (3) If static modifies a function, this function can only be called in the current file and cannot be called by other files. Variables modified by static are stored in the static variable area of the global data area, including global static variables and local static variables, all of which allocate memory in the global data area. They are automatically initialized to 0 during initialization.
- (4) When you do not want it to be released, you can use static to modify it. For example, modify an array stored in stack space in a function. If you do not want the array to be released when the function call ends, you can use static to modify it.
- (5) Consider data security (when the program wants to use global variables, it should first consider using static).
2.2 Static variables and ordinary variables
Static global variables have the following characteristics:
- (1) Static variables all allocate memory in the global data area, including the static local variables mentioned later;
- (2) Uninitialized static global variables will be automatically initialized to 0 by the program (the value of automatic variables declared inside a function body is random unless it is explicitly initialized, and automatic variables declared outside the function body will also be initialized to 0);
- (3) Static global variables are visible throughout the file in which they are declared, and are invisible outside the file.
Advantages:Static global variables cannot be used by other files; other files can define variables with the same name without conflict.
(1) The difference between global variables and global static variables
- 1) Global variables are global variables not explicitly modified with static. Global variables have external linkage by default, and their scope is the entire project. A global variable defined in one file can be used in another file by declaring 'extern global variable name'.
- 2) Global static variables are global variables explicitly modified with static. Their scope is the file in which the variable is declared. Other files cannot use them even with an extern declaration.
2.3 Static local variables have the following characteristics:
- (1) This variable allocates memory in the global data area;
- (2) A static local variable is initialized for the first time when the program executes to the declaration of the object, that is, subsequent function calls will not initialize it again;
- (3) Static local variables are generally initialized at the declaration. If there is no explicit initialization, they will be automatically initialized to 0 by the program;
- (4) It always resides in the global data area until the program finishes running. But its scope is a local scope. When the function or statement block that defines it ends, its scope also ends.
Generally, programs store newly generated dynamic data in the heap area, and automatic variables inside functions in the stack area. Automatic variables generally release space when the function exits. Static data (even static local variables inside functions) is also stored in the global data area. Data in the global data area is not released because of function exit.
Look at the following example:
Example
The output result is as follows:

3. Usage of static
3.1 In C++
The most basic usage of the static keyword is:
- 1. Variables modified by static belong to class variables and can be directly referenced byClass name.variable namedirectly reference it, without needing to new a class.
- 2. Methods modified by static belong to class methods and can be directly referenced byClass name.method namedirectly reference it, without needing to new a class.
Variables modified by static and methods modified by static collectively belong to the static resources of the class and are shared among class instances. In other words, if it changes in one place, it changes everywhere.
In C++, static members belong to the entire class rather than to a specific object. Static member variables are stored only once for all objects to share. Therefore, they can be shared among all objects. Using static member variables to achieve data sharing among multiple objects does not break the hiding principle, ensures security, and saves memory.
The definition or declaration of static members must include the keyword static. Static members can be used through the double colon, i.e.,<class name>::<static member name>。
3.2 Static class related
Calling static member functions and non-static member functions through the class name:
Error:
'Point::init' : illegal call of non-static member function
Conclusion 1:The non-static member functions of a class cannot be called through the class name.
Call static member functions and non-static member functions through an object of the class.
Compilation passes.
Conclusion 2: Objects of the class can use static member functions and non-static member functions.
Using non-static members of the class in a static member function of the class.
Compilation error:
error C2597: illegal reference to data member 'Point::m_x' in a static member function
Because a static member function belongs to the entire class, and space is allocated for it before the class instantiates an object, while a non-static member of the class can only have memory space after an object is instantiated, this call errors out. It is like using a variable before it has been declared.
Conclusion 3:Non-static members cannot be referenced in static member functions.
Using static members of the class in non-static member functions of the class.
Compilation passes.
Conclusion 4: Non-static member functions of a class can call static member functions, but the reverse is not possible.
Using static member variables of the class.
pressCtrl+F7Compilation is error-free, but a linking error is reported when pressing F7 to generate the EXE program.
error LNK2001: unresolved external symbol "private: static int Point::m_nPointCount" (?m_nPointCount@Point@@0HA)
This is because static member variables of the class must be initialized before use.
Inmain()Add before the functionint Point::m_nPointCount = 0;Compile and link again without errors, and running the program will output 1.
Conclusion 5: Static member variables of a class must be initialized before use.
Reflection summary:Static resources belong to the class, but exist independently of the class. From the perspective of the loading mechanism of class J, static resources are loaded when the class is initialized, whereas non-static resources are loaded when the class instantiates an object. Class initialization is earlier than class instantiation; for example,Class.forName("xxx")a method initializes a class but does not instantiate an object; it only loads the static resources of the class. Therefore, for static resources, it is impossible to know which non-static resources exist in a class. But for non-static resources, it is different: because they are produced after an object is instantiated, they can recognize all these things that belong to the class. So the answers to the above questions are very clear:
- 1) Can static methods reference non-static resources? No. Things that are produced only when an object is instantiated are simply not recognized by static resources that already exist after initialization.
- 2) Can static resources be referenced inside static methods? Yes, because they are all loaded during class initialization, and they all know each other.
- 3) Can static resources be referenced inside non-static methods? Yes. Non-static methods are instance methods, which are produced only after instantiating an object, so they recognize all content that belongs to the class.
(static modifying a class:This usage is much less common than the previous ones. In general, static cannot modify a class. If static modifies a class, it means the class is a static inner class (note that static can only modify an inner class), that is, an anonymous inner class. For example, the four rejection mechanisms in the thread pool ThreadPoolExecutor—CallerRunsPolicy, AbortPolicy, DiscardPolicy, DiscardOldestPolicy—are static inner classes. Content related to static inner classes will be covered specially when writing about inner classes.)
3.3 Summary:
- (1) Non-static members cannot be called in static member functions.
- (2) Static members can be called in non-static member functions. Because static members belong to the class itself and already exist before an object of the class is created, static members can be called in non-static member functions.
- (3) Static member variables must be initialized before use (e.g.int MyClass::m_nNumber = 0;), otherwise an error will occur at link time.
General summary: In a class, static can be used to modify static data members and static member methods.
Static data members
- (1) Static data members can realize data sharing among multiple objects. They are shared members of all objects of the class, occupying only one space in memory. If their value changes, the value of this data member in each object is also changed.
- (2) Static data members are allocated space when the program starts running and are not released until the program ends. As long as a static data member is specified in the class, space is allocated for it even if no object is defined.
- (3) Static data members can be initialized, but only outside the class body. If no initial value is assigned to a static data member, the compiler automatically initializes it to 0.
- (4) Static data members can be referenced by either the object name or the class name.
Static member functions
- (1) Like static data members, static member functions belong to the static members of the class, not to object members.
- (2) Non-static member functions have a this pointer, while static member functions do not have a this pointer.
- (3) Static member functions are mainly used to access static data members and cannot access non-static members.
Let's give another example using static member variables and functions of a class to deepen understanding. This example creates a student class. Objects of each student class will form a doubly linked list. A static member variable records the head of the doubly linked list, and a static member function outputs this doubly linked list.
Example
The program will output:

Original address: https://www.cnblogs.com/33debug/p/7223869.html