我試圖弄清楚什麼時候應該使用const編寫C++代碼。是pessimization的這些所有實施例或者是有益的寫代碼這樣?:C++ - 常量參數和類變量pessimization?
實施例1:
int findVal(const int OTHER_VAL) const
{
switch(OTHER_VAL)
{
case 1:
return 2;
default:
return 3;
}
}
實施例2:
enum class MobType
{
COW, CHICKEN, DOG, PIG
};
class BaseMob
{
protected:
BaseMob(const MobType TYPE) : TYPE(TYPE) { }
const MobType TYPE;
};
實施例3:
void showWorld(const World &world)
{
auto data = world.getData();
for (auto &i:data)
i.print();
}
知道該變量永遠不會被修改意味着當您嘗試瞭解其周圍的代碼時,您還有一件事要跟蹤。 – chris
「我試圖弄清楚何時應該在編寫C++代碼時使用const」 - - 只要有可能。 –
他們中的任何一個會以何種方式成爲悲觀主義者? – molbdnilo