如果我有这样的代码
class Node {
public:
Node *subnodes[10];
};
Node x = Node();
代码运行后是否保证x->subnodes[0] == nullptr
?我不是 C++ 专家,我发现 C++ 规范令人生畏。这在实践中是可行的,但是规范是否保证在这种情况下将 nullptr 放入数组的每个元素中(而不是说,潜在的垃圾)?到目前为止,我还没有通过找到权威的规范语言来说服自己,并且在野外我看到很多代码示例似乎不相信这是真的。所以,经过一段时间未能想出答案后,我转向你,堆栈 溢出 .提前致谢。
最佳答案
是的,这是有保证的。Node()
构造一个临时对象并执行 value initialization .结果,成员数组subnodes
的所有元素是 zero-initialized作为空指针。 x
从临时对象复制初始化,其成员也获得相同的初始化结果。 (因为 copy elision x
可能会直接进行值初始化,反正结果不会改变。)
if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor;
和
The effects of zero initialization are:
- If T is a scalar type, the object's initial value is the integral constant zero explicitly converted to T.
- If T is an non-union class type, all base classes and non-static data members are zero-initialized, and all padding is initialized to zero bits. The constructors, if any, are ignored.
- ...
- If T is array type, each element is zero-initialized.
- ...
顺便说一句:对于 default initialization喜欢
Node x;
,成员数组的元素将被初始化为不确定的值。
关于c++ - 在 C++ 中,指针类型数组的元素是否保证默认初始化为 nullptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62566438/