Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will C++ default-initialization set array elements to its default value?

Consider the following code:

#include <iostream>

using namespace std;

int main(){
  int* p = new int[2];
  for (int i = 0; i < 2; i++)
    cout << p[i] << endl;  
  return 0;
}

I run it several times. It always produces the following output:

0
0

Can I assume that C++ default-initialization set array elements to its default value? In this case, can I assume that p's element values are always set to 0?

I have read the following related questions. But they does not specifically address my case:

  • How to initialise memory with new operator in C++?

  • Operator new initializes memory to zero

like image 756
Jingguo Yao Avatar asked Dec 19 '22 12:12

Jingguo Yao


1 Answers

Can I assume that C++ default-initialization set array elements to its default value?

No, for default initialization:

  • if T is an array type, every element of the array is default-initialized;

and the element type is int, then

  • otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.

On the other hand, list initialization(since C++11) like int* p = new int[2]{}; or int* p = new int[2]{0};, or value initialization like int* p = new int[2](); will guarantee that, for int all the elements will be zero-initialized.

like image 130
songyuanyao Avatar answered Dec 21 '22 02:12

songyuanyao