Const before or after type?

I have the following code:

string const& operator[] (size_t index) const { return elems[index]; } 

if it is not:

 const string& 

?

+7
c ++
source share
3 answers

Cv qualifiers, such as const , are applicable to the fact that to their left, if there is nothing, in which case they apply to the law. For string const& , const is applied to the string on the left. For const string& , const is applied to the string on the right. That is, they are links to const string , so in this case it does not matter.

Some people prefer to have it on the left (e.g. const int ), because it reads from left to right. Some people prefer to have it on the right (e.g. int const ) to avoid using a special case ( int const * const more consistent than const int* const , for example).

+16
source share

const can be on either side of the data type, therefore:

" const int * " matches " int const * "

" const int * const " matches " 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 

Basic Rule: const applies to the thing left of it. If there is nothing on the left then it applies to the thing right of it. const applies to the thing left of it. If there is nothing on the left then it applies to the thing right of it.

+5
source share

In this context, it works anyway and refers to personal preferences and coding rules.

Some programmers prefer to place it after the type name to make it more consistent with other const uses. For example, if you declare a pointer in which the pointer itself (and not the pointer type) must be const , you need to place it after the asterisk:

 string * const ptr; 

Similarly, if you declare a member function const , it must go after the function declaration; eg:.

 class Foo { void func() const; }; 
+3
source share

All Articles