2
定義常量是否有最佳做法?這裏是一個小例子:將所有常量定義爲常量引用?
#include <vector>
struct mystruct {
std::vector<double> data;
mystruct() : data(100000000,0) {};
};
int main(){
mystruct A;
int answer = 42;
const mystruct& use_struct_option_1 = A; // quick
const mystruct use_struct_option_2 = A; // expensive
const int& use_answer_option_1 = answer; // good practice?
const int use_answer_option_2 = answer; // ubiquitous
}
顯然,初始化use_struct_option_2
這種方式是昂貴的,因爲mystruct
拷貝構造函數被調用,而初始化use_struct_option_1
的方式更快。 但是,這同樣適用於類型,如整數?
從我已經鎖定在我可以告訴大家,
const int use_answer_option_2 = answer;
比
const int& use_answer_option_1 = answer;
哪一個是最好更常見的代碼?
對於'int'的情況,選項1不會產生一個常數值;它是一個無法通過名稱use_answer_option_1來更改的值,但任何人都可以使用answer = 21;來更改引用所引用的內容。你必須決定這是否是你想要的。與結構類似;你呢,還是你沒有,關心修改你的'不斷引用'引用的數據的人?如果它很重要,那麼您需要一個副本,即使這意味着您將800 MiB添加到您的數據空間。如果沒關係,那麼對非常數數據的常量引用就可以了。 –