作为标题
#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-initialized到 0
。
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 ifT
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/