Static,const,inline three keywords in C + + in detail _c language

Source: Internet
Author: User
Tags constant modifier

First, about static
Static is a commonly used modifier in C + +, which is used to control the way variables are stored and visible, and I'll analyze the nature of the static modifier comprehensively from the reason and the effect of the static modifier.

the two main functions of static:

One, control storage mode
Static is introduced to tell the compiler to store variables in the static store of the program rather than on the stack space.

Cause:
A variable that is defined inside a function, when the program executes to its definition, the compiler allocates space for it on the stack, and 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 does it work if you want to save the value of this variable in a 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).

Solution:
Therefore, in C + +, a static is introduced to modify the variable, which instructs the compiler to save the variable in the static storage area of the program, thus achieving the goal and making the variable's access scope unchanged.

Ii. control visibility and connection types
Static also has the function of restricting the visible range of a variable to a compilation unit, making it an internal connection, at which point its antonym is "extern".

Static Action Analysis Summary:
Static always makes the stored form of a variable or object static, the connection becomes an internal connection, and for a local variable (already connected internally), it changes its storage only; for a global variable, which is already statically stored, it only changes its connection type.

Static members in a class
Causes and Effects:

1, need to interact among the objects of a class, that is, the need for a data object for the entire class rather than an object service.

2, at the same time and strive to not destroy the packaging of the class, that is, the requirements of this member hidden within the class, externally invisible.

The static member of the class satisfies the above requirements because it has the following characteristics: There is a separate storage area, which belongs to the entire class.

Attention:

1, for static data members, the connector will guarantee that it has a single external definition. 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.

2. 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 to access only static data and static member functions of the class.

Ii. about Const
Const is a commonly used type modifier in C + +, but I found in my work that many people use it just for a reason, so that sometimes it will be used right, but in some delicate occasions, it is not so lucky, the essence of the original, mostly because there is no understanding of the source. Here I will make an analysis of the Const. Back to its origin, the essence of the hope that we can understand the const help, according to the thinking of the undertaking relationship, divided into the following sections to elaborate.

Why is the const introduced in C + +

In what sense did the author of C + + introduce (or retain) The Const keyword based on what purpose? , this is an interesting and rewarding topic that helps to understand the Const.

1. As you know, C + + has a strict type of compiler system, which makes C + + program errors in the compile phase can be found many, so that the error rate is greatly reduced, so it has become a C + + and C, has a prominent advantage of one aspect.

2. A common preprocessing instruction in C #define VARIABLENAME VariableValue can be easily substituted for values,

This value substitution is outstanding in at least three aspects:

The first is to avoid the ambiguous meaning of the number appears, making the program semantics smooth and clear, the following example:
#define USER_NUM_MAX 107 This avoids the confusion of using 107 directly.

Second, can be easily adjusted and modified parameters, such as the above example, when the number of people from 107 to 201, into the changes here can be;

The third is to improve the execution efficiency of the program, because the use of the precompiled compiler for value substitution, do not need to allocate storage space for these constants, so the implementation of high efficiency.

In view of the above advantages, the use of predefined directives is ubiquitous in the program.

3. Speaking of which, you may be puzzled by the above 1 points, 2 points and the const what is the relationship? OK, then look down:

Although preprocessing statements have many advantages, they have a fatal disadvantage, that is, preprocessing statements are only simple value substitution and lack of type detection mechanism. Such a preprocessing statement cannot enjoy the benefits of strict type checking in C + +, which may be a potential cause of a series of errors.

4. Well, the first stage of the conclusion came out:

Conclusion: The initial purpose of the const rollout is to replace the precompiled instruction, to eliminate its drawbacks, and to inherit its advantages.

Now its form has become:

Const DataType VariableName = VariableValue;

Why is const a good place to replace a predefined statement?

What is the great avatar of the const, so that it can rallying a wave instead of a predefined statement?

First, the constant value, which is modified with const, is immutable, which is the basis for its substitution of predefined statements.

Second, it is obvious that it can also avoid the ambiguity of the number of the emergence of the same can be easily adjusted and modified parameters.

Third, C + + compilers usually do not allocate storage space for ordinary const constants. Instead, they are stored in a symbol table, which makes it a constant during compilation, without the operation of storing and reading memory, making it highly efficient, and this is an important basis for replacing predefined statements.

Here, I want to mention why this is also the basis for the substitution of predefined statements, because the compiler does not read the stored content, and if the compiler allocates storage space for const, it cannot be a constant during compilation.

Finally, the const definition, like a normal variable definition, is detected by the compiler for its type, eliminating the pitfalls of predefined statements.

A detailed analysis of the classification of const usage
1.const analysis of two kinds of pointers
int const *A; File://A variable, *a not variable
int *const A; File://A immutable, *a variable

Analysis: Const is a left-bound type modifier, and its left side of the type decorated with a type modifier, so the int const *a, does not qualify a. int *const limit A, *a is not qualified.

2.const qualified function Pass value parameter
void Fun (const int Var);
Analysis: The above defined parameters can not be changed in the function body. By the characteristic of value transfer, the change of Var in the function body does not affect the external function. Therefore, this qualification is not related to the user of the function, only to the creator of the function.

Conclusion: It is best to limit the function and screen the external caller so as not to cause confusion. If it can be rewritten as follows:

Copy Code code as follows:

void Fun (int Var)
{
const int & varalias = Var;
Varalias .....
.....
}

3. Value-type return value of the const-qualified function
const int FUN1 ();
Const MyClass FUN2 ();

Analysis: The above method to limit the return value of the function can not be updated, when the function returned to the internal type (such as FUN1), is already a numerical value, of course, can not be assigned to update, so, at this time the const meaningless, preferably removed to avoid confusion. When a function returns a custom type (such as Fun2), the type still contains variable members that can be assigned, so it makes sense at this point.

4. Transfer and return address
This kind of situation is most common, by the characteristic of address variable know, proper use const, meaning starkly expose anti-liberal.

5. member functions of the const-qualified class

Copy Code code as follows:

Class ClassName {

Public

int Fun () const;

.....

}


Note: The use of such a const form is a provision, and in order not to cause confusion. You use the const in the declaration and in the definition of this function, because the const is already part of the type information.

Gain capability: You can manipulate constant objects.

Incapacity: You cannot modify the data members of a class, and you cannot invoke other functions that are not const in a function.

Iii. about Inline
In the above talk about the const, the following to talk about inline this keyword, the reason for the inline placed in this position, because inline this keyword introduction reason and const very similar, the following is divided into the following sections to elaborate.

Reasons for introducing the inline keyword in C + +:
The inline keyword is used to define an inline function for a class, and the main reason for introducing it is to use it instead of a macro definition in the form of an expression in C.


An example of a macro definition in the form of an expression:
#define EXPRESSIONNAME (VAR1,VAR2) (VAR1+VAR2) * (VAR1-VAR2)

Why replace this form, and listen to my word:

1. first, let's talk about why you use this form of macro definition in C, C language is a highly efficient language, this macro definition in the form and use like a function, but it uses the preprocessor implementation, without the parameters of the stack, code generation, such as a series of operations, therefore, high efficiency, This is one of the main reasons it is used in C.

2. This macro definition is similar in form to a function, but when used, it is only a simple substitution in the preprocessor notation table, so it cannot detect the validity of the parameter, nor can it enjoy the benefit of the strict type checking of C + + compiler. In addition, its return value can not be coerced into a convertible suitable type, so that its use has a series of hidden dangers and limitations.

3. class and Class access control is introduced in C + +, so if an action or an expression involves a protected member of the class or a private member, you cannot use this macro definition to implement (because the this pointer cannot be placed in the right place).

4. The purpose of inline is to replace the macro definition in this form of expression, which eliminates its drawbacks while inheriting its advantages.

Why is inline a good substitute for the predefined form of an expression?

Corresponding to the above 1-3 points, elaborated as follows:

1. Inline the inline function of the class defined, the code of the function is put into the symbol table, replaced directly in use (like a macro), without the overhead of the call, and the efficiency is high.

2. Obviously, the inline function of a class is also a real function, and when the compiler calls an inline function, it first checks the type of its arguments to ensure that the call is correct. Then do a series of related checks, just like any real function. This eliminates its hidden dangers and limitations.

3. Inline can be a member function of a class, and of course you can use the protection and private members of the class in it.

When to use the inline function
First, you can use the inline function to completely replace the macro definition of an expression.

Also note that inline functions are generally used only when the content of the function is very simple, because the code for the inline function is expanded wherever it is invoked, and if the function is too complex, the consequences of code bloat are likely to outweigh the benefits of increased efficiency. The most important use of inline functions is the access function for the class.

How to use the inline function of a class

Simply mention the use of inline:

1. Define this function in the class

Copy Code code as follows:

Class classname{
.....
....
GetWidth () {return m_lpicwidth;}; If defined directly in a class, you can use the inline modifier without using the
....
....
}

2. Declare in class, define outside the class:
Copy Code code as follows:

Class classname{
.....
....
GetWidth (); If defined directly in a class, you can use the inline modifier without using the
....
....
}
Inline Classname::getwidth ()

{

return m_lpicwidth;

}


In this article, we talk about a special function, the inline function of a class, whose origin and characteristics are similar to the const in some way, and can be paired with the Const.

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.