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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With