Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make `new[]` default-initialize the array of primitive types?

Tags:

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?

like image 943
sharptooth Avatar asked Mar 18 '10 07:03

sharptooth


People also ask

How do you initialize a primitive array in Java?

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.

How do you initialize an array in new?

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 primitive types be instantiated?

Can array of primitive data type be instantiated? Yes.

Does new initialize to zero C++?

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.


1 Answers

int* p = new int[10]() should do.

However, as Michael points out, using std::vector would be better.

like image 66
sbi Avatar answered Sep 19 '22 21:09

sbi