我知道關於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