类型之前或之后的常量

Const before or after the type?

本文关键字:常量 或之后 类型      更新时间:2023-10-16

我有以下代码:

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

不应该是:

const string&

const这样的 Cv 限定符适用于它们左侧的任何内容,除非什么都没有,在这种情况下,它们适用于右侧。对于string const&const适用于其左侧的string。对于const string&const适用于其右侧的string。也就是说,它们都是对const string的引用,所以在这种情况下,它没有区别。

有些人喜欢把它放在左边(比如const int),因为它是从左到右读的。有些人喜欢把它放在右边(比如int const),以避免使用特殊情况(例如,int const * constconst int* const更一致)。

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

基本规则是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的其他用法更一致。例如,如果要声明指针本身(而不是指向的类型)const,则需要将其放在星号之后:

string * const ptr;

类似地,如果要声明一个const成员函数,它需要在函数声明之后;例如:

class Foo
{
    void func() const;
};