我知道几乎没有关于 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;
}
总结:制作值参数对于捕获一些逻辑错误很有用。这是最佳实践吗?您是否走到了将 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
}