const pointer and pointer to const in Cpp
March 6, 2017
C++
中文翻译好像有常量指针和指针常量这两种说法。然而翻译过来让我更加费解。还是英文更加直白。
pointer to const
const int b = 30;
const int * bptr = &b;
bptr
是一个指针,它指向的是一个类型为const int
的对象。可以对bptr
本身的内容(保存的地址)进行修改,但是不能对它指向的对象进行修改:
const int c = 31;
bptr = &c;
这样,bptr
就指向了另外一个const对象。
有个例外:可以让pointer to const指向一个nonconst对象。
int d = 32;
bptr = &d;
需要注意的是,即使d
变量是nonconst,仍然不能通过bptr
这个指针对b
进行修改:
// *bptr = 33; // error!
总之,
我可以指向const对象,也可以指向nonconst对象,你也可以修改我。但是,你不能修改我指向的*对象*。 — pointer to const
const pointer
int a = 3;
int * const aptr = &a;
aptr
是一个常量,同时是一个指针。不能对aptr
里面保存的地址进行修改。但是可以对aptr
所指向的对象进行修改:
*aptr = 4;
const reference
一个例子:
const int i = 42;
const int &ri = i;
例外:const reference 可以引用一个nonconst对象:
int j = 10;
const int &rj = &j;
这样做唯一的作用就是,不能够通过rj
这个引用来改变j
变量的值。这里和pointer to const
是一样的。
但是不能让一个nonconst reference引用一个const对象:
const int k = 30;
// int &rk = &k; // error!
总之指向const的指针或者引用可以指向(引用)nonconst对象。但是指向nonconst的指针或者引用不可以指向(const)对象。
这个问题以前就遇到过也弄明白了,然而过了很长时间又忘了。所以记在这里。
一段完整的测试程序:
// 2017/03/06 08:57:48
/*
const: const.cpp
g++ -Wall -std=gnu++11 const.cpp -o const
*/
#include <bits/stdc++.h>
// Pointers and const
using namespace std;
int main(int argc, char *argv[])
{
// we may store the address of a const object ONLY in a pointer to const
const double pi = 3.14;
// double *ptr = π // error!
const double *cptr = π
// *cptr = 10; // error: cannot assign to *cptr
// But there are two exceptions to the rule that the type of a pointer
// and the object to which it points must match:
// 1) we can use a pointer to const to point to a nonconst object:
double a = 2.17;
cptr = &a; // we can not change a through cptr
// pointer to const: I think I point to a const though I am not sure. T_T
// Maybe it is nonconst. But I won't (cannot) change its value. ^_^ Besides,
// You can change myself, but you can not change the OBJECT I point to.
int b = 0;
int *const bptr = &b; // bptr will ALWAYS point to b
// but you can change the object it points if that is not a const object:
*bptr = 1;
const double * const ppi = π // ppi is a const pointer to const object
// //////////////////////////////
// References
const int c = 8;
const int & cc = c;
// int & c1 = c; // error! we cannot assign directly to c,
// we also should not be able to use a reference to change c.
// But there is an exception: a reference to const may refer to an object
// that is not const
int i = 42;
const int &r1 = i;
int &r2 = i;
r2 = 43;
// r1 = 44; // error: can not change i through r1
// c++ programmers tend to abbreviate `reference to const` as `const reference`. There are non const references. A reference is not an object, so we cannot make a reference itself const. Because there is no way to make a reference refer to a different object, in some sense all references are const.
return 0;
}