[英]Behaviors of default initialization on struct fields
When code is written like that: 这样编写代码时:
#include <iostream>
using namespace std;
struct ID {
char *name;
int age;
};
int main() {
ID a;
cout << (long)(a.name) << endl;
cout << a.age << endl;
// cout << (a.name == nullptr) << endl;
return 0;
}
The result is: 结果是:
0
0
However, when it's written like that: 但是,当这样写时:
#include <iostream>
using namespace std;
struct ID {
char *name;
int age;
};
int main() {
ID a;
cout << (long)(a.name) << endl;
cout << a.age << endl;
cout << (a.name == nullptr) << endl;
return 0;
}
The result seem strange: 结果似乎很奇怪:
140735032148552
1545300144
0
How could these 2 versions vary greatly? 这两个版本的差异如何?
Because of undefined behavior . 由于行为不确定 。 Defining a local variable will not initialize it, the contents of the structure will be indeterminate, and using it will lead to said UB. 定义局部变量不会初始化它,结构的内容将是不确定的,并且使用它会导致所述UB。
I found the answer myself. 我自己找到了答案。 Thank you! 谢谢! Pileborg, Daniel and pstanisz. 皮尔博格,丹尼尔和帕斯坦尼斯。 Your answer and comments are of great help to me. 您的回答和评论对我有很大帮助。
My confusion came from a paragraph in "C++ Primer". 我的困惑来自“ C ++ Primer”中的一段。 In case anybody else has the same confusion, I write my understanding here. 万一其他人有同样的困惑,我在这里写下我的理解。
Original word: 原始字词:
Under the new standard, we can supply an in-class initializer for a data member. 在新标准下,我们可以为数据成员提供类内初始化程序。 When we create objects, the in-class initializers will be used to initialize the data members. 创建对象时,将使用类内的初始化程序来初始化数据成员。 Members without an initializer are default initialized (§ 2.2.1, p. 43). 没有初始化程序的成员将被默认初始化(第2.2.1节,第43页)。 Thus, when we define Sales_data objects, units_sold and revenue will be initialized to 0, and bookNo will be initialized to the empty string. 因此,当我们定义Sales_data对象时,units_sold和Revenue将被初始化为0,而bookNo将被初始化为空字符串。
-- "C++ Primer 5th edition" -“ C ++ Primer 5th Edition”
I had thought that fields in a struct follow the same default initialization rule as global variable (ie initialized to their zero values). 我以为结构中的字段遵循与全局变量相同的默认初始化规则(即,初始化为它们的零值)。 But it actually follows the same rule as local variables in a funtion, which is: 但实际上,它遵循与局部变量相同的规则,即:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.