c++ - new int[100] 和 new int[100]() 的区别;

标签 c++ c++11 initialization new-operator unique-ptr

作为标题

#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;
}

有什么区别?我试过两个输出都是零。

另外还有什么关于智能指针,如何确保它可以零初始化。

std::unique_ptr<int[]> p = std::make_unique<int[]>(100);

最佳答案

new int[100] 执行 default initialization ,所有元素都将被初始化为不确定的值。请注意,从中读取会导致 UB ,一切皆有可能。

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

new int[100]() 执行 value initialization ,因为所有元素的效果都是 zero-initialized0

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

4) otherwise, the object is zero-initialized.

编辑

std::make_unique采用第二种方式进行初始化。

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]())

附言:std::make_unique_for_overwrite采用第一种方式。

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])

关于c++ - new int[100] 和 new int[100]() 的区别;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62211102/

相关文章:

c++ - 铛。嵌套模板的二元运算符重载

c++ - 从派生类初始化 const fusion boost 列表

c++ - 与右值引用不一致的重载决议

C++ 模板化类给出 `error: non-template X used as template`

c++11 - 命名空间 ‘underlying_type_t’ 中的错误 ‘std’ 未在 project-OSRM 的 example.cpp 中命名模板类型

c++ - std::make_pair 和 std::make_optional 之间的一致性

c++ - 使用模板函数打印智能指针 vector

java - 有没有办法在 Java 中按需初始化对象?

java - 初始化 block 和指定范围的 block 之间有区别吗

python - 无效类型,必须是字符串或 Tensor [TensorFlow]