我知道关于const正确性的问题很少,它声明函数的声明及其定义不需要同意值参数。这是因为值参数的常量只在函数内部很重要。这很好:Const参数值的正确性
// header
int func(int i);
// cpp
int func(const int i) {
return i;
}
这样做真的是最佳做法吗?因为我从来没有见过任何人这样做。我已经看到了这个报价(不知道来源的)在其他地方这个已经讨论:
"In fact, to the compiler, the function signature is the same whether you include this const in front of a value parameter or not."
"Avoid const pass-by-value parameters in function declarations. Still make the parameter const in the same function's definition if it won't be modified."
第二段说,不要把常量的声明。我认为这是因为作为接口定义的一部分,值参数的常量是没有意义的。这是一个实现细节。
根据这个建议,是否也推荐指针参数的指针值? (因为你不能重新分配的参考这是在参考参数毫无意义。)
// 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 keyword - use liberally? Use of 'const' for function parameters
当常数值参数都是有用的例子:
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
}
它惹人“如果(i = j)的”错误在这种情况下,但没有捕捉到所有这些错误,所以我不会为这个特定的基本原理感到兴奋(因为你可以用变量来做同样的错误)。即使没有const,如果你告诉它你想要警告,你的编译器也会警告你。 – nobar 2009-11-13 04:29:52
'if(i = j)'让人兴奋的一点是要认识到常量值参数不仅仅是绒毛。迈克尔伯尔的例子甚至比这个更好。 – jmucchiello 2009-11-13 06:35:14
在不更改函数参数的情况下,应该对它们进行约束,因为A)它更安全,B)它是自记录的,C)它更易于调试。另外,原型和头文件应该标记为const。如果只是在函数头部完成,那很令人困惑。有关在函数中创建临时变量的争论是一种情况,您可能不需要声明参数const。这是我的2便士。 – 2011-09-19 20:52:23