The use of the Const keyword in C + + is very flexible, and using the const will greatly improve the robustness of the program, I found in various aspects of the information summarized below, hoping to help friends.
Const is a type modifier commonly used in C + +, which refers to a type that uses the type modifier const description, and the value of a constant type variable or object cannot be updated.
First, Const function
This is shown in the following table:
No. |
Role |
Description |
Reference Code |
1 |
You can define Const constants |
|
const int MAX = 100; |
2 |
Easy to type check |
Const constants have data types, and macro constants do not have data types. The compiler can perform type safety checks on the former, but only character substitution for the latter, no type security checks, and unexpected errors in character substitution |
void f (const int i) {...} // type check for incoming parameters, do not match to prompt |
3 |
Can protect something that's been modified. |
Prevent accidental modification and enhance the robustness of the program. |
void f (const int i) {i=10;//error!} // If you have modified in the function body I , the compiler will error |
4 |
It is easy to adjust and modify parameters. |
As with the definition of a macro, you can do the same, change |
|
5 |
Provides a reference for function overloading |
|
Class A { ...... void f (int i) {...} // a function void f (int i) const {...} // overloads of the previous function ...... }; |
6 |
Saves space and avoids unnecessary memory allocations |
const definition constants from the assembly point of view, just give the corresponding memory address, instead of the immediate number as defined by the definition, so the const defines the constant in the program run only one copy, and # Constants defined by define have several copies in memory |
#define PI 3.14159 // macro constants Const doulbe pi=3.14159; // no pi Put in ROM Double I=pi; // Now allocate memory for PI , no longer assigned! Double I=pi; // Macro substitution during compilation, allocating memory Double J=pi; // No memory allocation Double J=pi; // |
7 |
Increased efficiency |
The compiler typically does not allocate storage space for ordinary const constants, but instead saves them in the symbol table, which makes it a constant during compilation, without the storage and read memory operations, making it highly efficient |
|
Second, Const the Use
1 , Defining Constants
(1) The const modifier variable, the following two definitions form is essentially the same. The meaning of this is that the const-modified variant of type ' value ' is immutable.
TYPE Const VALUENAME = value;
Const TYPE ValueName = value;
(2) Change the const to an external connection, which is used to enlarge to the global, the memory is allocated at compile time, and can be uninitialized, just as a declaration, the compiler thinks it is defined elsewhere in the program.
extend const int ValueName = value ;
2 , referring to pin use const
(1) The pointer itself is a constant immutable
(char*) const pcontent;
const (char*) pcontent; The
(2) pointer points to something that is constant immutable
const ( char) *pcontent;
(char) const *PCONTENT; 
(3) both immutable
const char* const PCONTENT; 
(4) There is a difference between the lines along the * number:
If const is on the left side of * , const is used to modify the variable pointed to by the pointer, that is, the pointer to a constant,
if the const is on the right side of *, the const is the modifier pointer itself, that is, the pointer itself is a constant.
3 , use in functions CONST
(1) const modifier function parameters
A. The passed arguments cannot be changed within the function (meaningless because Var itself is a formal parameter)
void function (const int Var);
B. The contents of the parameter pointer are constant
void function (const char* Var);
C. The parameter pointer itself is constant immutable (also meaningless because char* var is also a formal parameter)
void function (char* const VAR);
D. Parameters are references, in order to increase efficiency and prevent modification. When modifying reference parameters:
void function (const class& Var); // reference parameters cannot be changed within a function
void function (const type& Var); // reference parameters are constants within a function immutable
Such a const reference pass and the most common function by the value of the effect is exactly the same, he forbade all changes to the referenced object, the only difference is that by value passing will first establish a copy of the class object, and then pass the past, and it passes the address directly, So this transfer is more efficient than passing by value. In addition, only the Const pass of the reference can pass a temporary object, because the temporary object is a const attribute, and is not visible, he has a local domain for a short time, so you cannot use pointers, only the const pass of the reference can catch this guy.
(2) const modifier function return value
The const modifier function returns a value that is not practical, and its meaning is basically the same as the const-modified ordinary variable and the pointer.
A.const int FUN1 () //this is actually meaningless, because the parameter return itself is the assignment.
B.Const int * FUN2 () //when calledconst int *pvalue = FUN2 ();
//we can putfun2 ()as a variable, that is, the pointer content is immutable.
C.int* Const FUN3 () //when calledint * Const PVALUE = fun2 ();
//we can putfun2 ()as a variable, that is, the pointer itself is immutable.
In General, when the return value of a function is an object, if it is declared as Const , many overloads of the operator are used. In general, it is not recommended to use The const-modifier function's return value type as an object or as a reference to an object. The reason for this is that if the return value is const for an object (const A test = A instance) or a reference to an object is const (const a& test = A instance), the return value has a const property, The return instance can only access the public (protected) data members and the const member functions in Class A, and it is not allowed to be assigned operations, which is rarely used in general cases.
4 , class-related const
(1) const modifier member variable
Const decorated class member function, which represents a member constant, cannot be modified,
     class A
{
..
const int nvalue; // Member constants cannot be modified
a (int x): Nvalue (x) {}; //
}
(2) The Const modifier member function
Const modifies the member function of the class, the member function cannot modify any non-const member function in the class. Usually written at the end of the function to modify.
    class A
{
  &NBSP, .....
       void function () const; // constant member function ,  .
// You cannot call any of the non- Const The member function.
}
For const class objects/pointers/references, only const member functions of the class can be called, so the most important role of the Const modifier member function is to restrict the use of Const objects.
A. The const member function is not allowed to modify any one of the data members of the object it resides on.
B. The const member function has access to the const member of the object , while the other member functions are not available.
(3) Const modifier class object/object pointer/object reference
const The decorated class object means that the object is a constant object, and any of its members cannot be modified. The same is true for object pointers and object references.
· Const- decorated object, any non-const member function of that object cannot be called because any non- const member functions have an attempt to modify member variables.
For example:
Class AAA
{
void Func1 ();
void Func2 () const;
}
Const AAA Aobj;
Aobj.func1 (); x
AOBJ.FUNC2 (); correct
Const aaa* aobj = new AAA ();
Aobj-> func1 (); x
Aobj-> Func2 (); correct
Third, the Const type conversion to non- Const Types of methods
Use const_cast for conversion.
Usage: const_cast <type_id> (expression)
The operator is used to modify the const or volatile properties of a type. In addition to const or volatile adornments, the type_id and expression types are the same.
· The constant pointer is converted into a very pointer, and still points to the original object;
· A constant reference is converted to a very literal reference and still points to the original object;
· A constant object is converted to a very mass object.
Iv. Use of Const Some of the recommendations
· The bold use of const will bring you endless benefits, but only if you have to figure it out;
· To avoid the most general assignment error, such as assigning a const variable to a value, the concrete visible study questions;
· Using const in parameters should use a reference or pointer instead of a generic object instance for the same reason;
· The three usages of const in member functions (parameters, return values, functions) should be used very well;
· Do not easily set the return value type of the function as const;
· In addition to overloading operators, it is generally not to make the return value type a const reference to an object;
· Any function that does not modify a data member should be declared as a const type.
V. Supplementary IMPORTANT Notes
· Constant restriction within a class: When using the initialization syntax of this class, the constant must be a constant expression
An integer or enum type that is initialized, and must be in static and const form.
· How to initialize constants inside a class: One method is to use static and const and initialize externally, for example:
Class A {public:a () {} private:static const int i; file://note must be static! };
const int a::i=3; Another very common method is to initialize the list: class A {public:a (int
i=0): Test (i) {} private:const int i; Another way is to initialize it externally,
· If in a non-const member function, the this pointer is just a class type, or if in the const member function,
The this pointer is a const class type, and if in a volatile member function, the this pointer is a
The volatile class type.
· The pointer returned by new must be of type Const.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C++_ a comprehensive summary of the const