Is it better to remove quot;constquot; in front of quot;primitivequot; types used as function parameters in the header?(删除“const是否更好?在“原始前面在标头中用作函数参数的类型?)
问题描述
在代码审查过程中,我的一位同事向我提到,在标头中用作函数参数的原始类型"前面的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:
将 const 排除在声明之外.它只是杂乱无章,不会影响客户端调用函数的方式.
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.
这篇关于删除“const"是否更好?在“原始"前面在标头中用作函数参数的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:删除“const"是否更好?在“原始"前面在标头中用作函数参数的类型?


基础教程推荐
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01