new [], delete [] complexity

后端 未结 4 1472
眼角桃花
眼角桃花 2021-02-07 10:23

I already know that the new[] operator first allocates memory and then calls the constructor for each element and that the delete[] operator first call

4条回答
  •  别跟我提以往
    2021-02-07 10:52

    It depends on your exact syntax:

    auto x = new unsigned[2];
    auto y = new unsigned[2]();
    ::std::cout << x[0] << "\n" << x[1] << "\n" << y[0] << "\n" << y[1] << "\n";
    delete[] x;
    delete[] y;
    

    gives the output (on my machine):

    3452816845
    3452816845
    0
    0
    

    Because one will be default initialized and the other value initialized.

    delete[] on the other hand is even simpler to understand: If your data type has a destructor, it will be called. The built in (and thus POD) types generally do not.

提交回复
热议问题