我今天在我的代码中发现了一个“错误”……但我不确定这个“错误”是否真的改变了编译后的代码。
考虑以下对double
、x
的引用的初始化。
double &x{*_data->x_double}; // x_double is a member variable of the struct
// _data, it is a pointer to another double
// eg, I have this somewhere else...
struct data
{
double *x_double;
};
data *_data = new data; // edit: duh, this has to be a pointer...
double another_x = 10.0;
_data->x_double = &another_x; // edit: pointer here too!
但是我犯了以下“错误”...(注意额外的 =
符号)
double &x={*_data->x_double};
此代码是从我的实际代码中复制的一个最小示例,其中我没有对 double 的引用,而是对大型对象的引用,例如 std::vector
。
引用变量的原因是它们在算法中使用,并且变量名非常长,所以我使用引用为这些变量创建了短别名。希望我这样做是有道理的...
那么,我已经“纠正”了“错误”,但我的输出编译代码是否真的发生了变化?
最佳答案
它们都是 list initialization .对于您的案例:
double &x={*_data->x_double};
是:
6) initialization of a named variable with a braced-init-list after an equals sign
和
double &x{*_data->x_double};
是:
1) initialization of a named variable with a braced-init-list (that is, a possibly empty brace-enclosed list of expressions or nested braced-init-lists)
在这种情况下,它们的效果完全相同。
关于C++ 引用变量的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40820462/