Every now and then I need to call new[]
for built-in types (usually char
). The result is an array with uninitialized values and I have to use memset()
or std::fill()
to initialize the elements.
How do I make new[]
default-initialize the elements?
To provide initial object references or primitive values other than the default, you have to address each element in the array. In the following code, we declare and create an array of Rectangle objects, and then create the Rectangle objects for each element: 1. Rectangle hotSpots[] = new Rectangle[10]; 2.
To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.
Can array of primitive data type be instantiated? Yes.
Apparently yes: [C++11: 5.3. 4/15]: A new-expression that creates an object of type T initializes that object as follows: If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed, the object has indeterminate value.
int* p = new int[10]()
should do.
However, as Michael points out, using std::vector
would be better.
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