#include <string>
struct T1 { int mem; };
struct T2
{
int mem;
T2() { } // "mem" is not in the initializer list
};
int n; // static non-class, a two-phase initialization is done:
// 1) zero initialization initializes n to zero
// 2) default initialization does nothing, leaving n being zero
int main()
{
int n; // non-class, the value is indeterminate
std::string s; // class, calls default ctor, the value is "" (empty string)
std::string a[2]; // array, default-initializes the elements, the value is {"", ""}
// int& r; // error: a reference
// const int n; // error: a const non-class
// const T1 t1; // error: const class with implicit default ctor
T1 t1; // class, calls implicit default ctor
const T2 t2; // const class, calls the user-provided default ctor
// t2.mem is default-initialized (to indeterminate value)
}
我目前正在查看参考指南,但有几个问题我不理解。
我已经运行了上面的代码,对于结构体T2,数据成员“int mem”没有出现在初始化列表中。据说t2.mem会被默认初始化为一个不确定的值。 但是当我运行这段代码时,t2.mem似乎被初始化为零?
0xcccccccc
。编辑:我刚在VS2017中测试了一下,t1.mem
和t2.mem
都像我预期的那样被初始化为0xcccccccc
。这个链接解释了原因:https://dev59.com/GnVC5IYBdhLWcg3w-mZO#127404 - drescherjm