The usage of the const keyword in C ++ is very flexible, and the use of const will greatly improve the robustness of the program. I will summarize the following information based on various aspects and hope to help my friends.
Const is a common type modifier in C ++. A common type is a type indicated by a const. The values of variables or objects of a common type cannot be updated.
I. Role of const
See the following table:
No.
Function
Description
Reference Code
1
Const constants can be defined.
Const int max = 100;
2
Easy type check
Const constants have data types, while macro constants do not. The compiler can perform type security checks on the former, while the latter only performs character replacement without type security checks, and unexpected errors may occur during character replacement.
Void F (const int I ){.........}
// Check the type of the input parameter. If the type does not match, a prompt is displayed.
3
Can protect modified things
Prevents unexpected modifications and enhances program robustness.
Void F (const int I) {I = 10; // error! }
// If I is modified in the function body, the compiler reports an error.
4
You can easily adjust and modify parameters.
Same as macro definition, it can be changed as long as it remains unchanged.
5
Provides a reference for function overloading.
Class
{
......
Void F (int I) {...} // a function
Void F (int I) const {...} // overload of the previous function
......
};
6
Saves space and avoids unnecessary memory allocation.
Const defines constants. From the assembly point of view, only the corresponding memory address is given, rather than the number of immediate values as # define. Therefore, the constant defined by const has only one copy during the program running, while # The constant defined by define has several copies in the memory.
# Define PI 3.14159 // constant macro
Const doulbe Pi = 3.14159; // pi is not put into ROM at this time
......
Double I = PI; // at this time, the PI is allocated with memory and will not be allocated later!
Double I = PI; // macro replacement during compilation and Memory Allocation
Double J = PI; // no memory allocation
Double J = PI; // macro replacement, memory allocation again!
7
Improved efficiency
Generally, the compiler does not allocate storage space for common const constants, but stores them in the symbol table, which makes it a constant during compilation without the operation of storage and read memory, this makes it highly efficient.
Ii. Use of const
1. Define Constants
(1) const modifies variables. The following two definitions are essentially the same. It means that the value of the type variable modified by const is unchangeable.
Type const valuename = value;
Const type valuename = value;
(2) Change const to an external connection to expand to the global level. during compilation, memory is allocated and Initialization is not allowed. It is only used as a declaration. The Compiler considers it defined elsewhere in the program.
Extend const int valuename = value;
2. Use const for pointers
(1) the pointer itself is a constant that is unchangeable.
(Char *) const Pcontent;
Const (char *) Pcontent;
(2) The Pointer Points to a constant that is unchangeable.
Const (char) * Pcontent;
(Char) const * Pcontent;
(3) Both are unchangeable.
Const char * const Pcontent;
(4) There are also different methods. Draw a line along the "*" sign:
If the const is on the left side of *, const is used to modify the variable pointed to by the pointer, that is, the pointer points to a constant;
If const is on the right side of *, const is to modify the pointer itself, that is, the pointer itself is a constant.
3. Use const in Functions
(1) const modifier function parameters
A. the passed parameters cannot be changed in the function (meaningless, because var itself is a form parameter)
Void function (const int var );
B. The content indicated by the parameter pointer is constant immutable.
Void function (const char * var );
C. The parameter pointer itself is a constant and immutable (also meaningless, because char * VaR is also a form parameter)
Void function (char * const var );
D. The parameter is a reference. In order to increase efficiency and prevent modification. When modifying referenced parameters:
Void function (const Class & var); // The referenced parameter cannot be changed in the function.
Void function (const type & var); // The referenced parameter is a constant in the function and cannot be changed.
Such a const reference transfer has the same effect as the value-based transfer of the most common function. It prohibits all modifications to the referenced object, the only difference is that a class object will be created before passing by value.
,
It then passes over, And it passes the address directly, so this transfer is more effective than passing by value. In addition, only the referenced const transmission can pass a temporary object, because the temporary object is a const attribute,
And it is invisible. It exists in a local domain for a short time, So pointer cannot be used. Only the referenced const transmission can capture this guy.
(2) const modifier function return value
The const modifier function does not actually return a lot of values. Its meaning is basically the same as that of the const modifier for common variables and pointers.
A. Const int fun1 () // This is actually meaningless, because the return value of the parameter itself is a value.
B. Const int * fun2 () // const int * pvalue = fun2 () when calling ();
// We can regard fun2 () as a variable, that is, the pointer content is immutable.
C.int * const fun3 () // int * const pvalue = fun2 () when calling ();
// We can regard fun2 () as a variable, that is, the pointer itself is immutable.
Generally, when the return value of a function is an object, if it is declared as const, it is mostly used for operator overloading. Generally, it is not recommended to use const to modify the type of the function's return value to a certain pair.
Such as a reference to an object. If the returned value is const (const a test =
Instance) or an object is referenced as const (const A & test = a instance)
If the returned value has the const attribute, only the public (protected) data member and the const member function in Class A can be returned, and the value assignment operation is not allowed.
.
4. class-related const
(1) const modifies member variables
A member function of the const modifier class, which indicates a member constant and cannot be modified. It can only be assigned a value in the initialization list.
Class
{
...
Const int nvalue; // The member constant cannot be modified.
...
A (int x): nvalue (x) {}; // values can only be assigned to the initialization list.
}
(2) const modifier member functions
If a const modifies a member function of a class, the member function cannot modify any non-const member function of the class. It is generally written at the end of the function.
Class
{
...
Void function () const; // constant member function, which does not change the member variable of the object.
// You cannot call any non-const member functions in the class.
}
For const class objects, pointers, and references, only the const member functions of the class can be called. Therefore, the most important function of const member functions is to restrict the use of const objects.
A. the const member function is not allowed to modify any data member of its object.
B. the const member function can access the const Member of the object, but other member functions cannot.
(3) const modifier Class Object/Object Pointer/Object Reference
· Const modifier Class Object indicates that this object is a constant object, and no member can be modified. The same is true for object pointers and object references.
· Const: any non-const member function of the object cannot be called, because any non-const member function will attempt to modify the member variables.
For example:
Class aaa
{
Void func1 ();
Void func2 () const;
}
Const AAA aobj;
Aobj. func1 (); ×
Aobj. func2 (); correct
Const AAA * aobj = new AAA ();
Aobj-> func1 (); ×
Aobj-> func2 (); correct
3. Convert the const type into a non-const type Method
Use const_cast for conversion.
Usage: const_cast <type_id> (expression)
This operator is used to modify the const or volatile attributes of the type. In addition to const or volatile modification, type_id and expression are of the same type.
· Constant pointers are converted to non-constant pointers and still point to the original object;
· Constant reference is converted to a non-constant reference and still points to the original object;
· Constant objects are converted to non-constant objects.
4. Const suggestions
· To use const boldly, this will bring you endless benefits, but the premise is that you must understand the original principles;
· Avoid the most common assignment errors. For example, assign values to the const variable;
· When using const in parameters, you should use references or pointers instead of common object instances, for the same reason as above;
· Const must be well used in three member functions (parameters, return values, and functions;
· Do not set the return value type of a function to const easily;
· Do not set the return value type as a const reference to an object except for the overload operator;
· Any function that does not modify data members should be declared as const type.
5. Additional important instructions
· Internal constant restrictions: when using the internal initialization syntax of this type, the constant must be a constant expression.
The initialized integer or enumeration type, which must be in the static and const forms.
· How to initialize internal constants of A Class: One method is static and const, Which is used externally. For example:
Class A {public: A () {} PRIVATE: static const int I; file: // note that it must be static! };
Const int A: I = 3; another common method is to initialize the list: Class A {public: A (int
I = 0): Test (I) {} PRIVATE: const int I ;}; another method is to initialize it externally,
· In a non-const member function, the this pointer is only of the class type. In a const member function,
The this pointer is of the const class type. In the volatile member function, the this pointer is
Volatile class type.
· The pointer returned by new must be of the const type.