Understanding Complicated const Type Declarations

C++ Primer 4/e 在pointers這裡還有一個忠告:『Part of the problem in reading const declarations arises because the const can go either before or after the type:

          string const s1;   // s1 and s2 have same type,
          const string s2;   // they're both strings that are const

 

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:


string s; typedef string *pstring; const pstring cstr1 = &s; // written this way the type is obscured pstring const cstr2 = &s; // all three decreations are the same type string *const cstr3 = &s; // they're all const pointers to string

 

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.』

中文版的是這樣說:『閱讀const宣告式時,部份問題出在const可出現於型別之前或之後:

string const s1;   // s1s2 有著相同的型別,
const string s2;   // 它門都是const strings

使用 typedefs 撰寫 const 定義式時,「const能夠出現於型別之前」這個事實容易困惑我們,到底定義了什麼型別:

        string s;
        typedef string *pstring;
        const pstring cstr1 = &s; // 這麼寫會使型別晦澀不明
        pstring const cstr2 = &s; // 三個宣告都是同一個型別
      string *const cstr3 = &s; // 它們都是 const pointers to string

把 const 放在 pstring 之後並由右向左閱讀,便能夠清楚地看到 cstr2 是個 const pstring,也就是 const pointer to strng。

不幸地是大多數 C++ 程式碼閱讀者都預期看到 const 出現在型別前面。因此,依照一般慣例先讓 const 出現或許是個好主意。但如果讓 const 出現在型別之後,對於宣告式的被理解度或許有幫助。』

希望我會很少用const型別,我的頭現在有點亂。

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *