Const之前或之后的类型?

use*_*311 7 c++

我有以下代码:

string const& operator[] (size_t index) const { return elems[index]; }
Run Code Online (Sandbox Code Playgroud)

不应该是:

const string&
Run Code Online (Sandbox Code Playgroud)

Jos*_*eld 17

Cv限定符就像const适用于它们左边的任何内容,除非没有任何内容,在这种情况下它们适用于右边.对于string const&,const适用string于其左侧.因为const string&,const适用string于它的权利.也就是说,它们都是引用const string,所以在这种情况下,它没有任何区别.

有些人喜欢在左边(比如const int),因为它从左到右阅读.有些人喜欢在右边(例如int const)使用它来避免使用特殊情况(int const * const比例如更加一致const int* const).


小智 5

const可以位于数据类型的任何一侧,因此:

" const int *"与" int const *" 相同

" const int * const"与" int const * const" 相同

int *ptr;           // ptr is pointer to int
int const *ptr;     // ptr is pointer to const int
int * const ptr;        // ptr is const pointer to int
int const * const ptr;  // ptr is const pointer to const int
int ** const ptr;       // ptr is const pointer to a pointer to an int
int * const *ptr;       // ptr is pointer to a const pointer to an int
int const **ptr;        // ptr is pointer to a pointer to a const int
int * const * const ptr;    // ptr is const pointer to a const pointer to an int
Run Code Online (Sandbox Code Playgroud)

基本规则是 const applies to the thing left of it. If there is nothing on the left then it applies to the thing right of it.