3

As title

#include <iostream>
int main() {
    auto* a = new float[1000000];
    auto* b = new float[10]();
    for(auto i=0; i<1000000; i++){
        std::cout << "a" << a[i] << std::endl;
    }
    for(auto i=0; i<10; i++){
        std::cout << "b" << b[i] << std::endl;
    }
    return 0;
}

what's the difference? I had tried both output is zero.

In addition what's about smart pointer, how to make sure it can zero initialized.

std::unique_ptr<int[]> p = std::make_unique<int[]>(100);
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Biao Cao
  • 141
  • 1
  • 10
  • One possible practical reason why uninitialized `a` contains zeros is that `new` gets zero-initialized memory from OS. For example, in Linux when you use `mmap` (and `new` can use it internally for allocation of large blocks) you get zero-initialized memory. – Evg Jun 05 '20 at 08:38
  • To clarify the previous comment: that's an explanation for your case, not a general rule. Reading uninitialized memory in C++ is Undefined Behavior. Anything can happen. – MSalters Jun 05 '20 at 08:49

1 Answers1

7

new int[100] performs default initialization, all the elements would be initialized to indeterminate values. Note that reading from them leads to UB, anything is possible.

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

new int[100]() performs value initialization, as the effect all the elements would be zero-initialized to 0.

3) if T is an array type, each element of the array is value-initialized;

4) otherwise, the object is zero-initialized.

EDIT

std::make_unique takes the 2nd way for initializing.

2) Constructs an array of unknown bound T. This overload only participates in overload resolution if T is an array of unknown bound. The function is equivalent to:

unique_ptr<T>(new typename std::remove_extent<T>::type[size]())

PS: std::make_unique_for_overwrite takes the 1st way.

5) Same as (2), except that the array is default-initialized. This overload only participates in overload resolution if T is an array of unknown bound. The function is equivalent to:

unique_ptr<T>(new typename std::remove_extent<T>::type[size])
songyuanyao
  • 169,198
  • 16
  • 310
  • 405