[c++] static keyword details

0. Preface

Static has a lot to do with the memory distribution of c + +. Before analyzing the static keyword, you'd better understand the memory distribution of c + + (it can be divided into five parts):

1. stack: storage areas allocated by the compiler when needed and automatically cleared when not needed. Store local variables and function parameters.
2. heap: it is usually allocated and released by the programmer, such as new and delete. If the programmer does not release it, it may be recycled by the OS at the end of the program.
3. Global data area (static area): the storage of global variables and static variables is in one area, the initialized global variables and static variables are in one area, the uninitialized global variables and uninitialized static variables are in another adjacent area. -Released by the system at the end of the program.
4. Read only constant area: it stores constants and cannot be modified (it can also be modified by improper means).
5. Code area: stores code (such as functions), which is not allowed to be modified (similar to constant storage), but can be executed (different from constant storage).

In c + +, the application of static can be divided into five types, as follows:

1. Static global variable

Adding the static keyword before the global variable is the static global variable;
Static global variables allocate memory in the global data area of the program, and they are not destroyed until the end of the program;

static int i = 0;  //Static global variable with initial value of 0
 
void fun()          //Every time fun is called, the value of global variable i increases by 1
{
	i += 1;
}

void main(){
	int k = 0;
	while(k < 100){
		fun();
		k++;
	} 
}

Differences between static global variables and general global variables:
... A static global variable is an internal property. It is visible in this file, starting from the definition of the variable until the end of the file, but not in other files (except for the include relationship).
... Common global variables are visible in other files of the same program, and the default is the external attribute.

For example (two files):
//a1.cpp

static int x = 10; //static global
int        y = 10; //Common global variable

//a2.cpp

#include<iostream>

extern int y;     //Use extern to let a2.cpp find the common global variable y defined in other files
extern int x;     //Error is reported. Static global variables will be file isolated
int main(){
	cout<<y;  //10
	y++;	  
	cout<<y;  //11

	//Cout < < x; / / error reported

	return 0;
}

It can be seen that with extern, you can use common global variables of other files, while static global variables cannot be used across files (except for "include")
We can say that static global variables have the function of file isolation. When we define static global variables, we do not need to worry about whether other files have defined global variables with the same name, which is very beneficial.

2. Static local variable

Static local variables are usually declared in the body of a function that will be called multiple times.
Characteristics of static local variables:

1) This variable allocates memory in the global data area; (but the scope of action is the same as the common local variable)
2) Static local variables are initialized for the first time when the program is executed at the declaration of the object, that is, function calls will not be initialized in the future;
3) The value of a static local variable is held until the next call (exit function, space is not reclaimed).

void fun()
{
   static x=0; //The scope of action is only in the body of the fun() function
   			 //It is initialized only on the first execution and not later.
   			 
   cout<<x<<endl;
   x++;
}

void  main(){

	fun(); //Output 0 the static local variable x is initialized
	fun(); //Output 1
	fun(); //Output 2
}

3. Static function

The function is defined as a static function by adding the static keyword to the return type of the function.
Static functions are similar to static global variables and have the function of file isolation.

static void fun (); // Declare static functions
void main()
{
   fun();
}
void fun ()			// Defining static functions
{
   cout<<"static function"<<endl;
}

4. Static data members

The above 1, 2 and 3 are functions of c and c + +.
The static data members and static member functions in the following 4 and 5 are only the concepts in c + +.

Static data members are one for each class, and common data members are one for each object (instance). Therefore, static data members are also called class variables, and common data members are also called instance variables.
In other words, static data members are common to all objects of the class.

Initialization of static data members needs to be outside the class.
Format: < data type > class name >: < static data member name > = < value >

Static data members can be accessed in two ways: class object name, static data member name, or class type name

The following is a piece of code passing the test, which can illustrate the above characteristics:

#include<iostream>
using namespace std;

class Myclass
{
public:
	Myclass(int a) {
		m_a = a;
		Sum += m_a;
	}

	int GetSum() { return Sum; }//Normal member functions can call static data members
	static int Sum;// Declare a static data member, a variable of the class, and all instances share a unique Sum

private:
	int m_a;
};
int Myclass::Sum = 0;// Define and initialize static data members

void main() {
	Myclass instance1(5);//Example 1
	cout << instance1.GetSum() << endl;   //5

	Myclass instance2(3);//Example 2
	cout << instance2.GetSum() << endl;  //8
	cout << instance2.Sum << endl;       //8
	cout << Myclass::Sum << endl;        //8

	cout << ++Myclass::Sum << endl;      //9
	system("pause");
}


}

5. Static member function

But compared with ordinary member function, 1) static member function does not have this pointer because it is not associated with any object. 2) Static member functions can only access static data members and static member functions, while ordinary member functions can access static member functions and static data members.

#include<iostream>
using namespace std;

class Myclass
{
public:
	Myclass(int a) {
		m_a = a;
		Sum += m_a;
	}

	static int GetSum() {                //Static member function, which can be defined directly in class
		//Cout < < m_a < < endl; / / error, unable to access non static members
		return Sum;
	}					
	static int Sum;                      // Declare static data members

private:
	int m_a;
};
int Myclass::Sum = 0;// Define and initialize static data members

void main() {
	Myclass instance1(5);
	cout << instance1.GetSum() << endl;   //5 instance1.GetSum() access form

	Myclass instance2(3);
	cout << Myclass::GetSum() << endl;   //8 MyClass:: getsum() access form
	cout << instance2.Sum << endl;       //8
	cout << Myclass::Sum << endl;        //8

	cout << ++Myclass::Sum << endl;      //9
	system("pause");
}
Published 49 original articles, won praise 22, visited 10000+
Private letter follow

Tags: Attribute

Posted on Thu, 20 Feb 2020 01:16:42 -0500 by Crys