[英]C++ initialization of reference variable
I spotted a "mistake" in my code today... But I'm not sure if the "mistake" actually changes the resulting compiled code. 我今天在我的代码中发现了一个“错误”...但我不确定“错误”是否实际上改变了生成的编译代码。
Consider initialization of the following reference to a double
, x
. 考虑将以下引用初始化为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!
However I made the following "mistake"... (notice the extra =
sign) 但是我做了以下“错误”...(注意额外=
标志)
double &x={*_data->x_double};
This code is a minimal example copied from my actual code, in which I don't have references to doubles, but references to large objects such as std::vector
's. 这段代码是从我的实际代码复制的最小例子,其中我没有对双精度的引用,而是对大对象的引用,例如std::vector
。
The reason for the reference variables is that they are used in an algorithm, and the variable names are very long, so I create shorted aliases for those variables using references. 引用变量的原因是它们在算法中使用,并且变量名称非常长,因此我使用引用为这些变量创建了短路别名。 Hope it makes sense why I did that... 希望我为什么这样做是有道理的...
So, I've "corrected" the "mistake" but has my output compiled code actually changed? 所以,我“纠正”了“错误”,但我的输出编译代码实际上已经改变了吗?
They're both list initialization . 它们都是列表初始化 。 For your cases: 对于您的情况:
double &x={*_data->x_double};
Is : 是:
6) initialization of a named variable with a braced-init-list after an equals sign 6)在等号后用braced-init-list初始化命名变量
And 和
double &x{*_data->x_double};
Is : 是:
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) 1)使用braced-init-list初始化一个命名变量(也就是说,一个可能为空的大括号括起来的表达式列表或嵌套的braced-init-lists)
Their effects are in this case exactly the same. 在这种情况下,它们的效果完全相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.