当未一致使用 const 时,如何使编译器至少发出警告

How to make compiler give at least a warning when const is not used consistently

假设我有一个代码

Test.h

class Test{
 public:
  int Func(const int a);
};

Test.cpp

int Test::Func(const int a){
  // some code
}

如果我去掉其中之一的常量,编译器仍会编译并给出零警告。即使在 GCC 中启用了 -Wall 和 -Wextra 并且在 Visual studio.

中启用了 /W4

例如Test.h

class Test{
 public:
  int Func(int a);
};

Test.cpp

int Test::Func(const int a){
  // some code
}

或Test.h

class Test{
 public:
  int Func(const int a);
};

Test.cpp 都可以正常编译。

int Test::Func(int a){
  // some code
}

如何让编译器检测到头文件和源文件之间 const 的使用不一致?

那些声明和定义都是一样的!在将声明与定义匹配时忽略顶级 const。所以这个组合还可以:

class C {
    void f(int);
};

void C::f(const int) {
}

因为 const 不算数,笼统地说。同样,

class C {
    void f(int) {
    }
    void f(const int) {
    }
};

是一个错误,因为它定义了两次相同的函数。

按照标准([dcl.fct]/5)

All declarations for a function shall agree exactly in both the return type and the parameter- type-list. ... After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” respectively. After producing the list of parameter types, any top-level cv-qualifiers modifying a parameter type are deleted when forming the function type. The resulting list of transformed parameter types and the presence or absence of the ellipsis or a function parameter pack is the function’s parameter-type-list.

所以即使一个有const int a而另一个有int a,两个声明(注意:一个定义就是一个声明)可以一致:top-level const是匹配声明时忽略。

但是,top-level const 在定义中很重要。如果参数是const int a,那么函数body不能修改a。在 header 中省略 const 并将其包含在定义中实际上是有意义的,因为调用者不需要知道按值传递的参数未被修改(这是一个实现细节) .这可能就是为什么没有警告的原因。 (在 header 中有 const 而在定义中没有 const 会很奇怪——也许应该有一个警告……)