gpt4 book ai didi

c++ - 将所有常量定义为 const 引用?

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:56 25 4
gpt4 key购买 nike

是否有定义常量的最佳实践?这是一个小例子:

#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 的情况下:

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

换句话说,选项 2 进行复制而选项 1 不进行。

决定是否要复制(即是否要在引用中看到对原始初始化程序的更改)。 mystruct 的情况相同。

关于c++ - 将所有常量定义为 const 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36379643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com