// header
int func(int i);
// cpp
int func(const int i) {
return i;
}
这真的是最佳实践吗?因为我从来没有见过有人这么做。在其他讨论中,我看到过此引语(不确定来源):“实际上,对于编译器而言,在值参数前面加上const还是不加都不会有任何区别。”
“避免在函数声明中使用传递方式为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
}
if (i = j)
感到兴奋的重点在于意识到 const 值参数并不只是花哨的东西。Michael Burr 的例子甚至比这个更好。 - jmucchiello