c++ - 在 C++ 中,指针类型数组的元素是否保证默认初始化为 nullptr?

标签 c++ arrays initialization value-initialization

如果我有这样的代码

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/

相关文章:

c++ - 使用 opencv/c++ 应用 canny 边缘检测器后出现 "Unhandled exception"错误

c - C中 union 的初始化

javascript - 如何在javascript中初始化后添加标记

java - 如何直接初始化 HashMap(以字面方式)?

c++ - 在公共(public)成员函数中访问私有(private)成员变量

c++ - 虚函数未解析为大多数派生类方法

java - 最简单循环中的效率案例

c++ - 如何处理 9 维矩阵的索引

arrays - (Dafny) 将一个数组的元素添加到另一个 - 循环不变式

python - 是否可以在 NumPy 中在没有循环的情况下逐行索引另一个二维数组?