Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "new int[8]()" equivalent to "new int[8]{}" in C++11?

Is new int[8]() equivalent to new int[8]{} in C++11?

In other words:

Does the C++11 standard guarantee each of new int[8]() and new int[8]{} returns a zero-initialized array?

like image 301
xmllmx Avatar asked Dec 26 '16 06:12

xmllmx


People also ask

What does new int [] mean?

new int[] means initialize an array object named arr and has a given number of elements,you can choose any number you want,but it will be of the type declared yet.

What is new int () in C++?

The purpose of new is to simply reserve memory for storing an int variable on the heap instead of the traditional stack. The main advantage of using heap is that you can store a large number of int variables like in an array of 100000 elements easily on the heap.

What does new in int Myarray new int n do?

new allocates an amount of memory needed to store the object/array that you request. In this case n numbers of int. The pointer will then store the address to this block of memory.

Does new int initialize to zero?

Yes. That's kind of my point. If you make a new variable and see that's it's zero, you can't straight away assume that something within your program has set it to zero. Since most memory comes ready-zeroed, it's probably still uninitialised.


1 Answers

new int[8]() will, by [dcl.init]/17.4, be value-initialized. Since it is an array, [dcl.init]/8.3 tells us that value initializing an array means to value-initialize each element.

new int[8]{} will, by [dcl.init.list]/3.2, invoke aggregate initialization on the array. Since there are no elements in the braced-init-list, each of the remaining elements in the array (ie: all 8) will be initialized "from an empty initializer list" ([dcl.init.aggr]/8). Which, after dancing through [dcl.init.list] again, leads you to 3.4, which tells you that "from an empty initializer list" for non-aggregate types means value-initializiation.

So yes, they both evaluate to the same thing.

like image 126
Nicol Bolas Avatar answered Sep 30 '22 16:09

Nicol Bolas