Preface
The const keyword is a constant rhetoric. To tell the compiler that a variable will not change in the program, you can declare it as Const.
However, the limit on the const keyword cannot just stay at this layer-it provides many more powerful functions.
Therefore, in many cases, the use of the const keyword is not a simple const + variable, and its usage is generally flexible.
Const keyword of pointer
The pointer defined by the const keyword on the left or right is completely different.
1 Const Int* PA = &;
Such a line of code defines a pointer PA pointing to the integer variable.
The function of the const keyword indicates that you cannot modify the value of variable A through the pointer Pa. Then, statements such as * pA = 1 will be reported by the compiler.
1 Int*ConstPa = &;
Such a line of code also defines a pointer PA pointing to the integer variable.
However, the const keyword is displayed on the right side of *, indicating that the pointer PA itself cannot be changed. Then, statements like Pa ++ will be reported by the compiler.
Const keyword of the iterator
The essence of the iterator is a pointer.
But see the statement that defines an iterator:
1STD: vector <Int>:: Iterator iter = V. Begin ();
This iterator points to the first element of the integer vector container v.
The problem is that * does not exist. How can I control whether the element pointed to by this pointer remains unchanged or does it remain unchanged?
The answer is, if you define the const iterator directly, as follows:
1 ConstSTD: vector <Int>:: Iterator iter = V. Begin ();
Then the defined pointer has a limit that the pointer itself remains unchanged, as if the const is placed on the right side. So how to define a const iterator that points to content remains unchanged but the pointer itself can change?
The method is as follows:
1STD: vector <Int>:: Const_iterator citer = V. Begin ();
In actual use, you will find that the next iterator is frequently used, and the first iterator is basically useless.
Const Keywords of member functions
Add the const keyword at the end of a member function declaration to add a constraint for the member function-the value of the member variable in the object to which the member function belongs cannot be changed.
Many people will ignore this usage, but it will play a lot of unexpected roles in debugging :).
A few instatements
1. Overload functions of operators should return the const type in many cases.
2. the const and non-const versions of member functions can be overloaded.
3. The role of the const member function is to make it possible to operate on the const object. This will be discussed and analyzed in detail later.
Summary
Const is a very practical keyword. It is very helpful for us to write efficient and sound code. We should try to use it to play its role.
Use const whenever possible