Assume that you are developing an underlyingProgramIt is inevitable to directly interact with the memory, and there will be many pointers in the program. Using pointers to operate on memory is very flexible, but it is also the root cause of many problems. Reducing these problems is this article.Article.
Before I officially begin, I need to familiarize myself with a method that is not commonly used.
Define a const pointer, for example:
Const int * PTR;
Of course, we can also write as follows:
Int const * PTR;
The above two statements are equivalent. I must emphasize that the second method is more formal, but the first method is more used. If you have just learned the C ++ language, you may confuse the second statement with int * const PTR; note the position of the const keyword and.
In actual situations, we may need a pointer to the pointer, for example:
Int ** PTR;
Now, we need to give him a value, such
PTR = & count_ptr;
Count_ptr is also a pointer. If the count_ptr type is int *, there is no problem. But what if the count_ptr type is const int? In this case, we must write as follows:
Int const ** PTR; // equivalent to const int ** PTR;
IfWhere is the count_ptr type int * const? The position of the const In the PTR definition statement must be changed. The correct syntax is as follows:
Int * const * PTR;
The const keyword is in the middle of two *, and the Definition Statement is hard to read. Of course, if we have mastered the correct reading method, there will be no problems. The pointer definition is read from the right to the left. First, observe the * closest to the PTR name. Its left side has const, and there is no keyword on the right side, which indicates that PTR points to a constant, it is a common variable. Then look to the left and observe the second one, which is also far away from PTR *. Its left side has no keyword, and the right side has const, which indicates PTR.Pointer to (count_ptr)It refers to a common variable, but it is a constant.
Similarly, we want to make PTR itself a constant, which can be written as follows:
Int * const PTR;
Note that the key word for making PTR itself a constant is the const on the right side of the first * (from right to left.
If count_ptr refers to a constant, you can write it as follows:
Int const * const PTR;
At this point, you will understand why I mentioned that method at the beginning. Keeping the const keyword closer to * makes this complicated Definition Statement easier to read.
Reproduced from: http://ropblog.net /? P = 17