簡體   English   中英

將所有常量定義為常量引用?

[英]Define all constants as const references?

是否有定義常量的最佳實踐? 這是一個小例子:

#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這種方式初始化use_struct_option_2代價高昂,因為調用了mystruct的復制構造函數,而初始化use_struct_option_1方式更快。 但是,這同樣適用於整數等類型嗎?

從我一直鎖定的代碼中我可以看出

const int use_answer_option_2 = answer;

const int& use_answer_option_1 = answer;

哪個更可取?

這些做不同的事情。 例如,在 int 情況下:

answer = 43;
cout << use_answer_option_1 << '\n';     // 43
cout << use_answer_option_2 << '\n';     // 42

換句話說,選項 2 會復制,而選項 1 不會。

決定是否要進行復制(即是否要查看引用中反映的對原始初始值設定項的更改)。 mystruct情況是一樣的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM