网上基本上是下面两种说法:常量指针(pointer to const)和指针常量(const pointer)
C++ Primer中文版(第5版,王刚 杨巨峰 译)中是下面两种说法:指向常量的指针(pointer to const)和常量指针(const pointer)
注意:这两个版本中“常量指针”的定义是相反的。
不如就用英文表示,理解起来更容易些。
这里的const为名词性质,to为指向性介词,to const为后置定语,表示“指向常量的”意思,更确切地说,pointer to const表示的是“无法通过该指针修改其指向的对象”,而它指向的对象不一定需要const修饰。
//以下两种语句均可编译通过 //1. int a=0x0f; const int* p_a; p_a=&a; //2. const int b=0xff; const int* p_b=&b; //以下语句(通过该指针修改指向对象的值)报错:表达式必须是可修改的左值 //*p_a=0x0d; //*p_b=0x0d;这里的const为形容词性质,表示“指针本身为常量”,在声明时需完成初始化,此后该指针不可更改(不可指向其他地址的意思)。
//const pointer初始化 int c=0xef; int* const p_c=&c; //以下语句正确 *p_c=0x01; //以下语句(指针重新赋值)报错:表达式必须是可修改的左值 //p_c=&a;类似的,还有对常量的引用(reference to const),表示“不能通过该引用修改它所绑定的对象”,同样,它绑定的对象不一定需要const修饰,与pointer to const有点像。
//以下两种语句均正确 //1. const int d=0xcc; const int& r_d=d; //2. int e=0xcd; const int& r_e=e; //通过该引用修改原对象时报错:表达式必须是可修改的左值 //r_d=0xff;但是与pointer to const的用法还是有差异的:
double f = 1.234; //以下语句正确 const int& r_f = f; //以下语句编译报错 //const int* p_f = &f;实际上,const int& r_f = f相当于
const int tmp=f; const int& r_f=tmp;从汇编来看的话更明显一些了
double f = 1.234; 00D51DEC movsd xmm0,mmword ptr [__real@3ff3be76c8b43958 (0D5CB78h)] 00D51DF4 movsd mmword ptr [f],xmm0 const int& r_f = f; 00D51DF9 cvttsd2si eax,mmword ptr [f] 00D51DFE mov dword ptr [ebp-58h],eax 00D51E01 lea ecx,[ebp-58h] 00D51E04 mov dword ptr [r_f],ecx其中,cvttsd2si指令对double进行了截断。
Emmm,先写这么多吧
