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型别,我的头现在有点乱。