Read it backwards (as driven by Clockwise/Spiral Rule ):
(向后读取(受“ 顺时针/螺旋规则”驱动):)
-
int*
- pointer to int (int*
-指向int的指针)
-
int const *
- pointer to const int (int const *
-指向const int的指针)
-
int * const
- const pointer to int (int * const
指向int的const指针)
-
int const * const
- const pointer to const int (int const * const
指向const int的const指针)
Now the first const
can be on either side of the type so:
(现在,第一个const
可以位于类型的任一侧,因此:)
If you want to go really crazy you can do things like this:
(如果您想发疯,可以执行以下操作:)
-
int **
- pointer to pointer to int (int **
-指向int的指针)
-
int ** const
- a const pointer to a pointer to an int (int ** const
指向int的指针的const指针)
-
int * const *
- a pointer to a const pointer to an int (int * const *
-指向int的const指针)
-
int const **
- a pointer to a pointer to a const int (int const **
-指向const int的指针)
-
int * const * const
- a const pointer to a const pointer to an int (int * const * const
指向int * const * const
的const指针的const指针)
- ...
(...)
And to make sure we are clear on the meaning of const
(并确保我们清楚const的含义)
const int* foo;
int *const bar; //note, you actually need to set the pointer
//here because you can't change it later ;)
foo
is a variable pointer to a constant integer.
(foo
是指向常量整数的变量指针。)
This lets you change what you point to but not the value that you point to. (这使您可以更改指向的内容,但不能更改指向的值。)
Most often this is seen with C-style strings where you have a pointer to a const char
. (最常见的情况是使用C样式的字符串,其中有指向const char
的指针。)
You may change which string you point to but you can't change the content of these strings. (您可以更改指向的字符串,但是不能更改这些字符串的内容。)
This is important when the string itself is in the data segment of a program and shouldn't be changed. (当字符串本身位于程序的数据段中并且不应更改时,这一点很重要。)
bar
is a constant or fixed pointer to a value that can be changed.
(bar
是指向可以更改的值的常量或固定指针。)
This is like a reference without the extra syntactic sugar. (这就像没有多余语法糖的参考。)
Because of this fact, usually you would use a reference where you would use a T* const
pointer unless you need to allow NULL
pointers. (由于这个事实,除非需要允许使用NULL
指针,否则通常会在使用T* const
指针的地方使用引用。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…