我知道关于 const 正确性的问题很少,其中指出函数的声明及其定义不需要就值参数达成一致。这是因为值参数的常量仅在函数内部重要。这可以:
// header
int func(int i);
// cpp
int func(const int i) {
return i;
}
这样做真的是最佳实践吗?因为我从来没有见过有人这么做过。我在其他地方看到过这句话(不确定来源):
“事实上,对于编译器来说,无论是否在值参数前面包含此 const,函数签名都是相同的。”
“避免在函数声明中使用 const 值传递参数。如果不被修改,仍应在同一函数的定义中将参数设置为 const。”
第二段说不要将 const 放在声明中。我认为这是因为值参数的常量作为接口定义的一部分是没有意义的。这是一个实施细节。
基于这个建议,对于指针参数的指针值是否也有建议? (它对引用参数没有意义,因为您无法重新分配引用。)
// header
int func1(int* i);
int func2(int* i);
// cpp
int func1(int* i) {
int x = 0;
*i = 3; // compiles without error
i = &x; // compiles without error
return *i;
}
int func2(int* const i) {
int x = 0;
*i = 3; // compiles without error
i = &x; // compile error
return *i;
}
Summary:设置值参数对于捕获一些逻辑错误很有用。这是最佳实践吗?您是否会极端地将 const 排除在头文件之外?它与 const 指针值一样有用吗?为什么或者为什么不?
一些参考:
C++ const 关键字 - 随意使用?
使用“const”作为函数参数
const 值参数何时有用的示例:
bool are_ints_equal(const int i, const int j) {
if (i = j) { // without the consts this would compile without error
return true;
} else {
return false;
}
// return i = j; // I know it can be shortened
}