C + + about variables

Source: Internet
Author: User
Tags class definition function definition

Scope: Range of valid variable names
Existence: A period in which a variable is present in a program.
Storage mode: auto, register, extern, static
Storage type: Stacks (stack): variables that are automatically allocated and purged. Such as: local variables and function parameters
Heap (heap): a space allocated by functions such as malloc.
(in C + + This is called free storage area, and the space of new is called heap)
Global/Static Storage: Stores global and static variables.
Constant Store: Storage constants (constant string, magic number, etc.), not allowed to modify.

Type

Add

Scope

Existence period

Class

External definition (outside of function)

Global variables (external variables)

In order to define the first use: extern external variables can be described.

Global

Full

Initialize once

Static external variables

File

Full

External array

Global

Full

static functions

File

N/A

N/A

normal function

Global

N/A

N/A

Internal definition (inside function)

Static local Array

Local

Full

Initialize once

Static local Variables

Only one value can be assigned outside of a function

Local

Full

Initialize once

Ordinary local variable (automatic variable)

Local

Local

All objects (variables, arrays, etc.) that exist for the whole period have an "initialization" feature, that is, only initialized once before the program starts (and then the initialization statement is skipped, while other assignment statements are not skipped).
They are all allocated in the global/static storage area.
The right value when they are initialized can be an initialization expression (consisting of the literal/symbolic constant/base operator exception of assignment and increment operator). 0 (including arrays) is automatically set if no initialization statement is made.

****************************************************************************************

There are two ways to use static: static in process programming and static in object-oriented programming. The former is applied to ordinary variables and functions and does not involve classes; the latter mainly describes the role of static in class.

Static in process-oriented design

Differences between global, local, static global, and static local variables

C + + variables have different scopes according to the different lifecycle of the defined location, and scope can be divided into 6 kinds: global scope, local scope, statement scope, class scope, namespace scope and file scope.

Viewing from scopes:

Global variables have global scope. Global variables can be used for all source files only if they are defined 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.

A static local variable has a local scope, it is initialized only once, and since the first time it is initialized until the end of the program, it differs from the global variable in that the global variable is visible to all functions, while the static local variable is always visible only to the function body that defines itself.

A local variable is also only a local scope, which is an automatic object (auto) that does not always exist during the run of the program, but only exists during the execution of a function, the variable is revoked, and the memory occupied by the function is retracted.

Static global variables also have global scope, which differs from global variables in that if a program contains more than one file, it acts on the file in which it is defined and does not function in other files, that is, a variable modified by the static keyword has a file scope. This way, even if two different source files have defined static global variables of the same name, they are also different variables.

From the allocated memory space:
Global variables, static local variables, static global variables are allocated space in the static storage area, and local variables in the stack allocated space

The global variable itself is the static storage mode, static global variables are of course also static storage mode. The two are not different in the way they are stored. The difference between the two is that the scope of the Non-static global variable is the entire source program, and when a source program consists of multiple source files, non-static Global variables are valid in each source file. A static global variable restricts its scope, that is, it is only valid within the source file that defines the variable, and it 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 only be common to functions within that source file, so it is possible to avoid causing errors in other source files.

1), static variables are placed in the program's static data store (data segment) (global visibility), so that the next call can also maintain the original assignment. This is how it differs from stack variables and heap variables.
2, variable with static to tell the compiler, itself only in the scope of the variable to be visible. This is the difference between it and the global variable.

From the above analysis, we can see that the change of the local variable to the static variable is the change of its storage mode that changes its lifetime. Changing the global variable to a static variable changes its scope and limits its use. So the static this specifier plays a different role in different places. Should be taken into consideration.

Tips:
A. If the global variable is only accessed in a single c file, the variable can be modified to a static global variable to reduce the coupling between modules;
B. If the global variable is only accessed by a single function, the variable can be changed to a static local variable of the function to reduce the coupling between modules;
C. When designing and using functions that access dynamic global variables, static global variables, and static local variables, you need to consider the problem of reentry, as they are all placed in the static data store and globally visible;
D. If we need a reentrant function, then we must avoid using the static variable in the function (such a function is called: a function with "internal memory" function)
E. 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, return to the wrong pointer.

-----------------------------------------------------------------------------------------------------------

Static global variables: changing scope, not changing storage location

Static local variables: Changing the storage location without changing the scope of the action

Static functions: Add the Static keyword before the return type of the function, and the function is defined as a static function. A static function, unlike a normal function, can only be visible in the file in which it is declared and cannot be used by other files.

A function defined in a source file can only be called by a function in this file, not by a function in the other file of the same program, which is also called an intrinsic function. To define an intrinsic function, simply add a "static" keyword before the function type.

---------------------------------------------------------------------------------------------------------------

Second, object-oriented static keywords (static keywords in a class)

Static data members have the following characteristics:

For non-static data members, each class object has its own copy. Static data members are treated as members of a class. No matter how many objects of this class are defined, static data members have only one copy in the program, and access is shared by all objects of that type. In other words, static data members are common to all objects of the class. For multiple objects of the class, static data members are allocated only once in memory for all objects to share. Therefore, the value of the static data member is the same for each object, and its value can be updated;

Static data members are stored in the global data area. Static data member definitions are allocated space, so they cannot be defined in class declarations. In Example 5, the statement int myclass::sum=0 is defined as a static data member;

Static data members comply with PUBLIC,PROTECTED,PRIVATE access rules like regular data members;

Because static data members allocate memory in the global data area and are shared by all objects of this class, it is not part of 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;

Static data member initialization differs from general data member initialization. The format for static data member initialization is:

"Data type >< class name >::< static data member name >=< value"

Static data members of a class have two forms of access:

Class object name >.< static data member name, or class type name >::< static data member name >

If the access permission of 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;

Static data members are primarily used when each object has the same attribute. For example, for a deposit class, the interest for each instance is the same. Therefore, interest should be set as a static data member of the deposit class. There are two benefits, first, that the interest data members share the memory allocated in the global data area, regardless of the number of deposit objects defined, thus saving storage space. Second, once the interest needs to change, as long as the change, then all the deposit of the object of interest all change over;

There are two advantages to using static data members compared to global variables:

Static data members have no access to the global namespace of the program, so there is no possibility of conflict with other global names in the program;

can realize information hiding. Static data members can be private members, and global variables cannot;

2. Static member function

As with static data members, we can also create a static member function that serves all of the class's services rather than the specific object of a particular class. Static member functions, like static data members, are internal implementations of a class and are part of the class definition. Ordinary member functions implicitly imply a this pointer, the this pointer points to the object itself of the class, because the ordinary member function is always specific to the specific object of a class. Typically, this is the default. such as the function fn () is actually THIS->FN (). However, a static member function does not have the this pointer because it is not associated with any object, as opposed to a normal function. In this sense, it does not have access to non-static data members belonging to the class object, nor does it have access to non-static member functions, and it can only invoke the rest of the static member functions.

For static member functions, you can summarize the following points:

A function definition that appears outside the class body cannot specify a keyword static;

Static members can access each other, including static member functions accessing static data members and accessing static member functions;

Non-static member functions can access static member functions and static data members arbitrarily;

Static member functions do not have access to non-static member functions and non-static data members;

Because there is no extra overhead for this pointer, static member functions have a slight increase in speed compared to the global functions of a class;

Calling a static member function, you can use the member access operator (.) and (->) call static member functions for objects of a class or pointers to class objects, or you can use the following format directly:

Class name >::< static member function name > (parameter table)

Calls a static member function of a class.

***************************************************************************************

Static statically variable declaration character. In declaring its program block, subroutine block or function inside valid, value hold, allocate memory space throughout program, compiler default value 0.

is a commonly used modifier in C + +, which is used to control how variables are stored and visible.

2. Why should we introduce static?

A variable that is defined inside a function, when the program executes to its definition, the compiler allocates space on the stack, as you know, the space the function allocates on the stack is released at the end of the function execution, which creates a problem: How to save the value of this variable in the function to the next call. The easiest way to think about it is to define a global variable, but there are many drawbacks to defining it as a global variable, the most obvious disadvantage being that it destroys the scope of the variable's access (so that the variables defined in this function are not just controlled by this function).

3. When do I use static?

A data object is required to serve an entire class rather than an object, while trying not to break the encapsulation of the class, which requires that the member be hidden inside the class and not visible externally.

4. Static internal mechanism:

Static data members must exist when the program starts running. Because a function is invoked in the program's run, static data members cannot allocate space and initialize within any function.

In this way, it has a space allocation of three possible places, one is the header file of the outer interface of the class, where there are class declarations, and the internal implementation of the class definition, where the member function of the class is defined, and the third is the global data declaration and definition at the front of the application's main () function.

Static data members cannot be defined in the declaration of a class (only data members can be declared) in order to physically allocate space. A class declaration declares only the "Dimensions and Specifications" of a class and does not carry out actual memory allocations, so it is wrong to write a definition in a class declaration. It also cannot be defined as an external definition of a class declaration in a header file, because that would result in multiple definitions of it in a source file that uses the class.

Static is introduced to tell the compiler to store variables in the static store of the program rather than on the stack, static

Data members are initialized sequentially in the order in which they appear, and note that when static members are nested, the nested members are initialized. The order of elimination is the inverse order of initialization.

5, Static Advantages:

Memory can be saved because it is public to all objects, so for multiple objects, static data members are stored only one place for all objects to share. 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, ensuring that all objects access the updated value of the same, this can improve time efficiency.

6. When referencing static data members, the following format is used:

< class name >::< static member name >

If the access permission of a static data member is allowed (that is, a member of public), it can be in the program, in the format

To refer to static data members.

7, Attention matters:

(1) A static member function of a class is an object that belongs to an entire class, not a class, so it has no this pointer, which causes

It can only access static data and static member functions of a class.

(2) Static member functions cannot be defined as virtual functions.

(3) because the static member is declared in the class, the operation is outside, so the address operation is somewhat special

, the variable address is a pointer to its data type, and the function address type is a "nonmember function pointer."

(4) because the static member function does not have the this pointer, it is almost equivalent to the nonmember function, and the result

has created an unexpected benefit: to become a callback function that allows us to add C + + and c-based X W

The Indow system is combined and successfully applied to the thread function.

(5) Static does not increase the time and space overhead of the program, instead, she shortens the subclass's access to the static members of the parent class

Time, saving the memory space of the child class.

(6) Static data members precede the < definition or description > with the keyword static.

(7) The static data member is stored statically, so it must be initialized.

(8) Static member initialization differs from general data member initialization:

Initialization is done outside the class body, without the preceding static, so as not to be confused with a general static variable or object;

The private,public of the access rights control character of the member is not added when initializing;

The scope operator is used when initializing to indicate the class to which it belongs;

So we get the format of the static data member initialization:

< data type >< class name >::< static data member name >=< value >

(9) To prevent the parent class from being affected, you can define a subclass with the same static variable as the parent class to mask the effects of the parent class. Here's one thing to note: we say that static members are shared by the parent class and subclass, but we have the duplicate definition of static members, and this will not cause errors. No, our compiler uses a neat trick: name-mangling to generate a unique flag.

Article Source: Flying Connaught Net (http://www.diybl.com/course/3_program/c++/cppjs/20090902/173451.html)

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.