Explanation of static and const

Source: Internet
Author: User
I. Static: static is a common modifier in C ++. It is used to control the storage and visibility of variables, next I will talk about the reason and role of the static modifier, and fully analyze the essence of the static modifier.

Static:

1. Storage control method:

Static is introduced to inform the compiler that the variables are stored in the static storage area of the program rather than the stack space.

1. Cause: when the program executes the variable defined in the function to its definition, the compiler allocates space for it on the stack, the space allocated by the function on the stack is released at the end of the function execution. This creates a problem: If you want to save the value of this variable in the function to the next call, how to implement it?
The easiest way to think of is to define a global variable, but defining a global variable has many disadvantages, the most obvious drawback is that the access range of the variable is broken (so that the variables defined in this function are not controlled by this function ).

2. Solution: Therefore, static is introduced in C ++ to modify the variable, which can instruct the compiler to save the variable in the static storage area of the program, this achieves the goal and keeps the access range of this variable unchanged.

2. control visibility and connection type:

Static also has a function, which limits the visible scope of the variable to the compilation unit and makes it an internal connection. In this case, its antonym is "extern ".

Static analysis summary: static always changes the storage form of variables or objects to static storage, and the connection mode to internal connections. For local variables (internal connections already exist ), it only changes the storage mode. For global variables (which are already in static storage), it only changes the connection type.

Static member in the class:

1. Causes and functions:

1) interaction between objects in a class is required, that is, a data object must serve the entire class rather than a certain object.

2) at the same time, we strive not to undermine the encapsulation of the class, that is, this member is required to be hidden inside the class and invisible to the outside world.

The static member of the class meets the preceding requirements because it has the following features: it has an independent storage zone and belongs to the entire class.

2. Note:

1) for static data members, the connector ensures that it has a single external definition. Static data members are initialized sequentially according to the sequence in which they appear. Note that when static members are nested, make sure that the nested members have already been initialized. The order of cancellation is the reverse order of initialization.

2) The static member function of the class belongs to the entire class rather than the class object, so it does not have the this pointer, which leads to the ability to only parse static data and static member functions of the class.

Ii. Const:

Const is a type modifier commonly used in C ++. It is divided into the following parts.

Why is const introduced in C ++?

What is the purpose of the C ++ initiator to introduce (or retain) the const keyword? This is an interesting and useful topic and is helpful for understanding Const.

1. as we all know, C ++ has a strict type compilation system, which allows many errors of C ++ programs to be found in the compilation stage, greatly reducing the error rate, it has also become an outstanding advantage in comparison with C ++.

2. A common preprocessing command # define variablename variablevalue in C can be easily used for value substitution. This value substitution has at least three advantages:

The first is to avoid the appearance of numbers with vague meanings, so that the program semantics is fluent and clear, as shown in the following example:
# Define user_num_max 107 avoids the confusion caused by using 107 directly.

Second, you can easily adjust and modify parameters. In the preceding example, when the number of people changes from 107 to 201, you can modify the parameters here,

Third, it improves the execution efficiency of the program. Because the pre-compiler is used for value substitution, it does not need to allocate storage space for these constants, so the execution efficiency is high.

In view of the above advantages, the use of such predefined commands is everywhere in the program.

3. Speaking of this, you may be confused about the relationship between the first and second points and the const?

The pre-processing statement has many advantages, but it has a fatal disadvantage, that is, the pre-processing statement is only a replacement of simple values and lacks a type detection mechanism. In this way, the pre-processing statement cannot enjoy the advantage of strict C ++ type checks, which may cause a series of errors.

4. Now, the first stage has come to the conclusion:
Conclusion: The initial purpose of const is to replace precompiled commands, eliminate its disadvantages, and inherit its advantages.

Now its form is changed:

Const [datatype] [variablename] = variablevalue;
Why can const replace predefined statements?

1. First, the constant value modified by const is non-mutable, which is the basis for replacing predefine statements.

2. Second, it is obvious that it can also avoid the appearance of numbers with vague meanings, and it is also convenient to adjust and modify parameters.

3. third, the C ++ compiler usually saves them in the symbol table instead of allocating storage space for common const constants, which makes them a constant during compilation, without the storage and read memory operations, the efficiency is also very high. At the same time, this is also an important basis for replacing predefine statements. Here, I would like to mention why this is also the basis for it to replace the pre-defined statements, because the compiler will not read the stored content, if the compiler allocates storage space for const, it cannot be a constant during compilation.

4. Finally, the const definition is like a normal variable definition. It will be checked by the compiler for its type, eliminating the hidden danger of predefine statements.

Classification of const usage

1. const is used for Pointer Analysis in two cases:
Int const * A; file: // a variable, * a variable
Int * const A; file: // A is not variable, * A is variable

Analysis: const is a type modifier that is left-bound. It is the type Modifier on its left and a type modifier. Therefore, int const is limited to * a, not limited to. Int * const limits a, not *.

2. Const limits the passing value parameters of the function:

Void fun (const int var );
Analysis: The preceding statement specifies that parameters cannot be changed in the function body. According to the characteristics of value transfer, the changes of VaR in the function body do not affect the function exterior. Therefore, this limitation has nothing to do with the function user and is only related to the function writer.
Conclusion: It is best to limit the internal function to block external callers to avoid confusion. The following code can be rewritten:

Void fun (INT var ){
Const Int & varalias = var;
Varalias ....
.....
} 3. Const: const int fun1 ();
Const myclass fun2 ();
Analysis: The preceding statement limits that the return value of a function cannot be updated. When the function returns an internal type (for example, fun1), it is already a value. Of course, it cannot be assigned an update, at this time, const is meaningless. It is best to remove it to avoid confusion. When the function returns a custom type (such as fun2), this type still contains variable members that can be assigned values, so it makes sense at this time. 4. Transfer and return address: This is the most common case. It can be seen from the characteristics of address variables that the appropriate use of const is significant. 5. const limits the member functions of the class: The member functions of the class are followed by const, indicating that this function will not make any changes to the data members of this Class Object (accurately speaking, non-static data members, other functions that are not const cannot be called in the function; Class classname {
Public:
Int fun () const;
.....
}

Note:: A const-modified member function (that is, the const is placed behind the function parameter table, not before the function or in the parameter table). It can only read data members and cannot change data members; member functions without const modification are readable and writable for data members. A constant object (that is, a const object) can call a const member function, rather than a non-const modified function. Just as data of non-const type can assign values to the variable of const type, otherwise, it is not true.

Ability to obtain: const-qualified member functions can be called by the const object of the class.
Capacity Loss: you cannot modify the data members of a class or call other functions that are not const in a function.The following is a complete example:# Include <iostream>; <br/> # include <string>; <br/> using namespace STD; </P> <p> class student {<br/> public: <br/> Student () {}< br/> Student (const string & nm, int SC = 0) <br/>: Name (NM), score (SC) {}</P> <p> void set_student (const string & nm, int SC = 0) <br/>{< br/> name = Nm; <br/> score = SC; <br/>}</P> <p> const string & get_name () const <br/>{< br/> return name; <br/>}</P> <p> int get_score () const <br/>{< br/> return score; <br/>}</P> <p> PRIVATE: <br/> string name; <br/> int score; <br/> }; </P> <p> // output student's name and score <br/> void output_student (const student & Student) <br/>{< br/> cout <student. get_name () <"/t"; <br/> cout <student. get_score () <Endl; <br/>}</P> <p> int main () <br/>{< br/> Student Stu ("Wang ", 85); <br/> output_student (Stu); <br/>}A Class of student is designed. The data members include name and score, two constructor functions are available, and one is set Member Data function set_student (). Each has a function get_name () that obtains name and score () and get_score (). Note that both get_name () and get_score () are followed by const, and set_student () is not followed by (nor can there be const ).

First, let's talk a little bit about the problem. Why is const added before get_name. If there are no two const, get_name () returns a reference to the name of the private data member. Therefore, the value of the Private member name can be changed through this reference, as shown in
Student Stu ("Wang", 85); <br/> Stu. get_name () = "Li ";That is, the name is changed from the original "Wang" to "Li", which is not what we want to happen. Therefore, add const before get_name () to avoid this situation.

Therefore, the member functions of const should be added after get_name () and get_score (). Can it be modified without const? The answer is yes! However, the cost is that the const object cannot call these two non-const member functions. For exampleConst string & get_name (); // both functions should be set to const type <br/> int get_score (); <br/> void output_student (const student & Student) <br/>{< br/> cout <student. get_name () <"/t"; <br/> // If get_name () and get_score () are non-const member functions, this and the next call are incorrect <br/> cout <student. get_score () <Endl; <br/>}Because the student parameter represents a reference to a const student object, student cannot call non-const member functions such as set_student (). If the get_name () and get_score () member functions also become non-const types, student. get_name () and student. the use of get_score () is invalid, which makes it difficult for us to solve the problem.

Therefore, we have no reason to oppose the use of Const. When adding const, we should add const, so that apart from non-const objects, the const object can also call it.

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.