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);
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]()
performsvalue 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 isvalue-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 ifT
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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.