Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ are elements of an array of pointer type by default guaranteed to be initialized to nullptr?

If I have code like so

class Node {
public:
    Node *subnodes[10];
};
Node x = Node();

is it guaranteed after that code runs that x->subnodes[0] == nullptr?

I'm no expert at C++, and I find C++ specs daunting. This works out in practice, but is it guaranteed by the spec that nullptr is put in each element of the array in this case (as opposed to, say, potentially garbage)? I haven't convinced myself by finding authoritative spec language to that effect so far, and out in the wild I see lots of examples of code seeming not to trust that this is true. So, after some time failing to come up with the answer, I turn to you, stackoverflow. Thanks in advance.

like image 618
mhd Avatar asked Jun 25 '20 01:06

mhd


1 Answers

Yes, it is guaranteed.

Node() constructs a temporary object and performs value initialization. As the result, all the elements of the member array subnodes are zero-initialized as null pointer. x is copy-initialized from the temporary object and its members get the same initialization result too. (Because of copy elision x might be value-initialized directly, anyway the result won't change.)

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;

and

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.
  • ...

BTW: For default initialization like Node x;, the elements of the member array would be initialized to indeterminate values.

like image 184
songyuanyao Avatar answered Nov 02 '22 21:11

songyuanyao