简体   繁体   中英

Define all constants as const references?

Is there a best practice to define a constant? Here is a small example:

#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
}

Obviously, initializing use_struct_option_2 that way is expensive because the copy constructor of mystruct is called whereas the way of initializing use_struct_option_1 is quicker. However, does the same apply to types such as integers?

From the code I've been locking at I can tell that

const int use_answer_option_2 = answer;

is much more common than

const int& use_answer_option_1 = answer;

Which one is preferable?

These do different things. For example, in the int case:

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

In other words, option 2 makes a copy and option 1 doesn't.

Decide whether you want to make a copy or not (ie whether you want to see changes to the original initializer reflected in your reference). The mystruct case is the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM