常量指针和指向常量的指针

网上基本上是下面两种说法:
常量指针(pointer to const)和指针常量(const pointer)

C++ Primer中文版(第5版,王刚 杨巨峰 译)中是下面两种说法:
指向常量的指针(pointer to const)和常量指针(const pointer)

注意:这两个版本中“常量指针”的定义是相反的。

不如就用英文表示,理解起来更容易些。

pointer to const

这里的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 pointer

这里的const为形容词性质,表示“指针本身为常量”,在声明时需完成初始化此后该指针不可更改(不可指向其他地址的意思)。

//const pointer初始化
int c=0xef;
int* const p_c=&c;
//以下语句正确
*p_c=0x01;
//以下语句(指针重新赋值)报错:表达式必须是可修改的左值
//p_c=&a;

reference to const

类似的,还有对常量的引用(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,先写这么多吧

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值