C + + static global, local variable---18

Source: Internet
Author: User

Original blog, reprint please indicate the source--Zhou Xuewei http://www.cnblogs.com/zxouxuewei/

Static is used in two ways: static in process-oriented programming and static in object-oriented programming. The former applies to ordinary variables and functions, and does not involve classes; the latter mainly describes the role of static in classes.

I. For static in process design

C + + variables can be divided into 6 different scopes according to the different lifecycles of the defined locations: global scopes, local scopes, statement scopes, class scopes, namespace scopes, and file scopes.
    from the scope view:
1. Global variables have global scope. A global variable can be used for all source files simply by defining it in one source file. Of course, other source files that do not contain global variable definitions need to declare the global variable again with the extern keyword.

2. Static local variables have local scope (static), which is initialized only once, since the first time it is initialized until the end of the program runs, it differs from global variables in that global variables are visible to all functions, whereas static local variables are always visible to the body of the function that defines itself.
3. Local variables are also only local scope, it is an automatic object (auto), it does not persist during the program run, but only during the execution of the function, the function of the execution of a call after the end of the variable is revoked, the memory occupied by the recovery.
4. Static global variables have global scope (static), which differs from global variables in that if a program contains multiple files, it acts on the file in which it is defined and does not work in other files, that is, repaired by the static keyword

The decorated variable has a file scope.

  From allocating memory space, see:

1. Global variables, static local variables, static global variables are allocated space in the static storage, and local variables allocated space in the stack, new out of the space in the heap

2. Global variables themselves are static storage, and static global variables are, of course, static storage methods. The two are not different in how they are stored. The difference between the two is that the scope of the non-static global variable is the whole source program, when a source program consists of multiple source files, non-static global variables are valid in each source file

3. A static global variable restricts its scope, which is valid only within the source file that defines the variable, and cannot be used in other source files of the same source program. Because the scope of a static global variable is limited to one source file, it can be common only for functions within that source file, so you avoid causing errors in other source files.

1), static variables will be placed in the program's static data store (data segment) (globally visible), so that the next call can also maintain the original assignment. This is the difference between the stack variable and the heap variable. When the pointer is called, if you want to return a local variable value, the return value can be in static mode, otherwise the pointer will fly away.

2), variable with static to tell the compiler, itself only within the scope of the variable is visible. This is the difference between it and the global variable. From the above analysis, it can be seen that changing the local variable to a static variable changes its storage mode, which changes its life time. Changing a global variable to a static variable changes its scope and limits its scope of use. So the function of the static descriptor is different in different places. Should be taken into consideration.

A. If the global variable is accessed only in a single C file, you can modify the variable to a static global variable to reduce the coupling between the modules;
B. If the global variable is accessed only by a single function, the variable can be changed to a static local variable of the function to reduce the coupling between the modules;
C. When designing and using functions that access dynamic global variables, static global variables, and static local variables, you need to consider the reentrant problem, because they are all placed in a static data store and are globally visible;

D. If we need a reentrant function, then we must avoid using the static variable in the function (a function called "Internal memory" function)

The static variable condition must be used in the function: for example, when the return value of a function is a pointer type, it must be the address of the static local variable as the return value, and if it is the auto type, it is returned as the wrong pointer.

Static global variable: Change the scope without changing the storage location
Static local variable: Change the storage location without changing the scope

Static functions: The function is defined as a static function by adding the static keyword before the return type of the function. A static function differs from a normal function in that it can only be seen in the file that declares it and cannot be used by other files.

If a function defined in a source file can only be called by a function in this file, but not by a function in the other file of the same program, this function is also called an intrinsic function. Define an intrinsic function by simply adding a "static" keyword before the function type.

Second, the object-oriented static keyword (the static keyword in the Class)
1. Static data members
Static data members have the following characteristics:
1. For non-static data members, each class object has its own copy. Static data members are treated as members of the class. Regardless of how many objects of this class are defined, static data members have only one copy in the program and are shared by all objects of that type. In other words, a static data member is common to all objects of that class.

For multiple objects of this class, static data members are allocated only once for all objects to be shared. Therefore, the value of the static data member is the same for each object, and its value can be updated;

2. Static data members are stored in the global data area. Static data members are defined when they are allocated space, so they cannot be defined in a class declaration.

3. Static data members comply with PUBLIC,PROTECTED,PRIVATE access rules like normal data members;

4. Because static data members allocate memory in the global data area, all object shares of this class are shared, so it does not belong to a particular class object, and its scope is visible when no class object is generated, that is, we can manipulate it without producing an instance of the class, so you can go directly through the < class type name >::< Static member name > call.

5. Static data member initialization differs from general data member initialization. The static data member is initialized in the format: Data type >< class name >::< static data member name >=< value
6. A static data member of a class has two types of Access: Class object name >.< static data member name, or class type name >::< static data member name.
7. If the access permission of the static data member is allowed (that is, the member of public), the static data member can be referenced in the program according to the above format;
8. Static data members are used primarily when each object has the same property. For example, for a deposit class, the interest is the same for each instance. Therefore, interest should be set as a static data member of the deposit class. Here are two benefits:

First, regardless of how many deposit class objects are defined, interest data members share the memory allocated in the global data area, thus saving storage space.

Second, once the interest needs to be changed, the interest in all the deposit classes will change over once.

There are two advantages to using static data members compared to global variables:
① static data members do not enter the program's global namespace, so there is no possibility of conflicts with other global names in the program;
② can implement information hiding. A static data member can be a private member, while a global variable cannot;

2. Static member functions
A. As with static data members, we can also create a static member function that serves the entire service of a class rather than a specific object of a class. Static member functions, like static data members, are internal implementations of the class and are part of the class definition.

Ordinary member functions generally imply a this pointer, which points to the object of the class itself, because ordinary member functions are always specific to the specific object of a class. Typically, this is the default. such as the function fn () is actually THIS->FN (). But compared to the normal function,

A static member function does not have the this pointer because it is not associated with any object. In this sense, it cannot access non-static data members that belong to a class object, nor can it access a non-static member function, which only calls the rest of the static member functions.

For static member functions, you can summarize the following points:
1. A function definition that appears outside the class body cannot specify a keyword static;
2. Static members can be accessed from one another, including static member functions that access static data members and access static member functions;
3. Static member functions and static data members can be accessed arbitrarily by non-static member functions;
4. Static member functions cannot access non-static member functions and non-static data members;
5. Because there is no additional overhead for this pointer, the static member function has a slight increase in speed compared to the global function of the class;
6. Call a static member function, which can be accessed with the member access operator (.) and (a) call a static member function for an object of a class or pointer to a class object, or you can use the following format: class name >::< static member function name (parameter table)

7. Static variable declarator. In declaring its program block, the subroutine block or function is valid internally, the value remains, the memory space is allocated throughout the program, and the compiler defaults to 0. is a commonly used modifier in C + +, which is used to control how variables are stored and visible.

B, why to introduce static?

A variable defined inside a function, when the program executes to its definition, the compiler allocates space on the stack, and you know that the space allocated by the function on the stack is freed at the end of the function execution, which creates a problem: If you want to save the value of this variable in a function to the next

How is it implemented? The easiest way to think of is to define a global variable, but there are many drawbacks to defining a global variable, and the most obvious disadvantage is that it destroys the scope of access to the variable (the variable defined in this function is not only controlled by this function).

C, when to use static?
A data object is required to serve the entire class rather than an object, while at the same time trying not to break the encapsulation of the class, which requires that the member be hidden inside the class and not visible externally.
D, the internal mechanism of static:
A static data member must exist at the beginning of a program run. Because a function is called in a program run, a static data member cannot allocate space and initialization within any function.
In this way, its space allocation has three possible places, one is as the outer interface of the class header file, there is a class declaration (this sentence may not be), and the second is the internal implementation of the class definition, there is a class member function definition, three is the main () function of the application before the global data declaration and definition.
Static data members are actually allocated space, so they cannot be defined in the declaration of a class (only data members can be declared). A class declaration declares only "dimensions and specifications" of a class and does not actually allocate memory, so it is wrong to write a definition in a class declaration. It also cannot be defined externally in the header file for the class declaration, because that would cause duplicate definitions in multiple source files that use the class. Static is introduced to tell the compiler that the variables are stored in the program's static store rather than on the stack, and that static data members are initialized sequentially in the order in which they are defined, noting that when static members are nested, the nested members are guaranteed to be initialized. The order of elimination is the inverse order of the initialization.

E, the advantages of static:
Can save memory because it is public to all objects, so for multiple objects, static data members are stored only one place for all objects to be shared. The value of a static data member is the same for each object, but its value can be updated.

As long as the value of the static data member is updated once, it is guaranteed that all objects access the same value after the update, which can improve time efficiency.
F, when referencing static data members, use the following format: < class name >::< static member name >
If the access permission for a static data member is allowed (that is, a member of public), the static data member can be referenced in the program in the format described above.

G, note:  
(1) The static member function of a class is an object of the entire class rather than a class, so it does not have the this pointer, which causes   to access only the static data and static member functions of the class.  
(2) cannot define a static member function as a virtual function.  
(3) because a static member is declared in a class, it operates on its own, so it takes an address operation, which is somewhat special   the variable address is a pointer to its data type, and the function address type is a "nonmember function pointer."  
(4) since the static member function does not have this pointer, it is almost identical to the nonmember function, resulting in an unexpected benefit: being a callback function allows us to combine C + + and c-based X Window System, but also successfully applied to thread functions.  
(5) static does not increase the space-time overhead of the program, but instead shortens the subclass's access   time to the static members of the parent class, saving the memory space of the subclass.  
(6) static data members precede the < definition or description > with the keyword static.  
(7) A static data member is stored statically, so it must be initialized.  
(8) Static member initialization differs from general data member initialization: &NBSP;
initialization is performed outside the class body, and is not preceded by static, to avoid confusion with a general static variable or object, &NBSP;
Initialization is not Add the member's access control private,public, etc.;  
initializes the class by using the scope operator,  
So we derive the format of the static data member initialization: < data type >& lt; class name >::< static data member name >=< value > 
(9) to prevent the effect of the parent class, you can define a static variable in the subclass that is the same as the parent class to mask the effect of the parent class. Here's one thing to note: we say that static members are shared by the parent and subclass, but we have statically defined static members, does that cause errors?

No, our compiler uses a neat trick: name-mangling is used to generate unique flags.

In an architecture that uses segment memory management (such as Intel's 80x86 system), the BSS segment (Block Started by Symbol segment) usually refers to a chunk of memory that is used to hold uninitialized global variables in the program, and generally the BSS segment will be zeroed when initialized. The BSS segment is a static memory allocation, where the program is zeroed out at the outset. For example, after a program such as C has been compiled, the initialized global variable is saved in the. Data segment, and the uninitialized global variable is saved in the. BSS segment.
The post-compilation statements of the general C language are compiled into machine code, saved in the. Text field, and the initialized global variables and local static variables are saved in the. The data segment, uninitialized global variables, and local static variables are generally placed in a called. " BSS "in the section. We know that uninitialized global variables and local static variables default to 0, and they can also be placed in the. Data segment, but because they are all 0, it is not necessary for them to allocate space in the. Data segment and hold data 0. They do take up memory space when the program is running, and the executable file must record the sum of all uninitialized global variables and local static variables in the. BSS section. So the. BSS segment is only reserved for uninitialized global variables and local static variables, and it has no content, so it does not occupy space in the file.

C + + static global, local variable---18

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.