Pointers and the const Qualifier

There are two kinds of interactions between pointers and the const qualifier: We can have pointers to const objects and pointers that are themselves const.

More details about this topic can be found in 4.2.5 section in C++ Primer,Fourth Edition(Chinese p.110).

The following example is used to illustrate this topic.

 


Notice:
Pointers and Typedefs

The use of pointers in typedefs (Section 2.6) often leads to surprising results. Here is a question almost everyone answers incorrectly at least once. Given the following,

  

what is the type of cstr? The simple answer is that it is a pointer to const pstring. The deeper question is: what underlying type does a pointer to const pstring represent? Many think that the actual type is

 

That is, that a const pstring would be a pointer to a constant string. But that is incorrect.

 

The mistake is in thinking of a typedef as a textual expansion. When we declare a const pstring, the const modifies the type of pstring, which is a pointer. Therefore, this definition declares cstr to be a const pointer to string. The definition is equivalent to


Advice: Understanding Complicated const Type Declarations

 

Part of the problem in reading const declarations arises because the const can go either before or after the type:

When writing const definitions using typedefs, the fact that the const can precede the type can lead to confusion as to the actual type being defined:

Putting the const after pstring and reading the declaration from right to left makes it clearer that cstr2 is a const pstring, which in turn is a const pointer to string.

Unfortunately, most readers of C++ programs expect to see the const before the type. As a result, it is probably a good idea to put the const first, respecting common practice. But it can be helpful in understanding declarations to rewrite them to put the const after the type.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值