2012-07-06 68 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. 
}