删除“const"是否更好?在“原始"前面在标头中用作函数参数的类型?

2022-01-11 00:00:00 header constants c++ primitive-types

在代码审查过程中,我的一位同事向我提到,在标头中用作函数参数的原始类型"前面的const"是没有意义的,他建议删除这些const".他建议在这种情况下只在源文件中使用const".原始类型是指int"、char"、float"等类型.

In the code review process, one of my coworkers mentioned to me that "const"s in front of "primitive types" used as a function parameter in a header is meaningless, and he recommended to remove these "const"s. He suggested using "const" only in the source file in such cases. Primitive types mean types such as "int", "char", "float", etc.

以下是示例.

example.h

int ProcessScore(const int score);

example.cc

int ProcessScore(const int score) {
  // Do some calculation using score
  return some_value;
}

他的建议如下:

example.h

int ProcessScore(int score);  // const is removed here.

example.cc

int ProcessScore(const int score) {
  // Do some calculation using score
  return some_value;
}

但我有点困惑.通常情况下,用户只会看头文件,所以如果头文件和源文件不一致,可能会造成混淆.

But I'm somewhat confused. Usually, the user will look at only the header, so if there is inconsistency between the header and the source file, it might cause confusion.

有人可以给点建议吗?

推荐答案

对于所有类型(不仅仅是原语),函数声明中的顶级 const限定符是忽略.所以下面四个都声明了同一个函数:

For all types (not just primitives), the top level const qualifiers in the function declaration are ignored. So the following four all declare the same function:

void foo(int const i, int const j);
void foo(int i, int const j);
void foo(int const i, int j);
void foo(int i, int j);

然而,在函数 body 中不会忽略 const 限定符.在那里它可能对 const 正确性产生影响.但这是该功能的实现细节.所以普遍的共识是这样的:

The const qualifier isn't ignored inside the function body, however. There it can have impact on const correctness. But that is an implementation detail of the function. So the general consensus is this:

  1. 将 const 排除在声明之外.它只是杂乱无章,不会影响客户端调用函数的方式.

  1. Leave the const out of the declaration. It's just clutter, and doesn't affect how clients will call the function.

如果您希望编译器捕获对参数的任何意外修改,请将 const 留在定义中.

Leave the const in the definition if you wish for the compiler to catch any accidental modification of the parameter.

相关文章