2012-07-06 69 views
1

我可以声明foo(const T& var)以便我知道var不会被更改。指针的常量说明符

指针的等效格式为foo(const T* var)

在过去,我试过那些,与iterator/const_iterator有关的错误让我感到恼火,我只是倾向于使用(T* var)而不考虑常量。

是否有一个好的文档来声明强制指针所指向内容的函数不会改变'?

回答

7

你有什么已经是一个指针,禁止指针的内容改变。您可以通过使用“读倒退”的规则看到这一点:

const T* var  <===== left to right from this read 

阅读倒退:

var是一个指向T是恒定的

这是

不同
T* const var 

其中的内容如下:

var是常数指针T

的差别在这里的是,常数是var,而不是T;这意味着您可以通过取消引用var来更改T,但不能更改var指向的内容。

当然,你可以在同一时间有两个以上的:

const T* const var 
+0

怎么样的迭代器相关的错误? – eugene 2012-07-09 00:57:10

+0

@Eugene:如果你可以更具体...哪个错误?从什么代码? – Jon 2012-07-09 07:08:24

0

(从2 simple variable initialization question

一个非常好的经验法则关于const

从右至左读取声明。

(见Vandevoorde/Josutiss “C++模板:完全指南”)

如:

int const x; // x is a constant int 
const int x; // x is an int which is const 

// easy. the rule becomes really useful in the following: 
int const * const p; // p is const-pointer to const-int 
int const &p;  // p is a reference to const-int 
int * const * p;  // p is a pointer to const-pointer to int. 

自从我遵循这个原则进行的拇指,我从来没有曲解这种声明再次。

(:sisab retcarahc-REP无吨,sisab nekot-REP无薄膜电致发光-OT-thgir NAEM我hguohT:潮

同样,你可以写你的函数签名,这条规则:

void foo (int const * const p) 

现在,p是const-int的常量指针,这意味着在函数体内,不能让p指向别的东西,也就是说你不能改变指针,也不能改变它指向的东西。

p正在一个const指针是真的只有你的函数体的相关信息,您应该忽略来自头文件信息:

// foo.h 
void foo (int const *p); 

然后

// foo.cc 
void foo (int const * const p) { 
    // Here, the const serves you as the implementor as an additional 
    // safety gear. 
}