Operator New and Memory Initialization
The new operator is commonly known to allocate memory without initializing it. However, a recent code example reveals a scenario where memory appears to be initialized to zero upon allocation using new. This raises questions about the actual behavior of the operator.
The code:
#include <iostream> int main() { unsigned int *wsk2 = new unsigned int(5); std::cout << "wsk2: " << wsk2 << " " << *wsk2 << std::endl; delete wsk2; wsk2 = new unsigned int; std::cout << "wsk2: " << wsk2 << " " << *wsk2 << std::endl; return 0; }
Outputs:
wsk2: 0x928e008 5 wsk2: 0x928e008 0
The first allocation and initialization of wsk2 to the value 5 operates as expected. However, the second allocation and assignment of wsk2 to a new unsigned int without an initializer results in a value of 0.
Upon further investigation, it becomes apparent that there are two versions of the new operator:
This behavior also applies to arrays:
A custom test using placement new confirms that the zero initialization indeed occurs:
#include <new> #include <iostream> int main() { unsigned int wsa[5] = {1, 2, 3, 4, 5}; unsigned int *wsp = new(wsa) unsigned int[5](); std::cout << wsa[0] << "\n"; // If these are zero then it worked as described. std::cout << wsa[1] << "\n"; // If they contain the numbers 1 - 5 then it failed. std::cout << wsa[2] << "\n"; std::cout << wsa[3] << "\n"; std::cout << wsa[4] << "\n"; }
Outputs:
0 0 0 0 0
This demonstrates that the new operator supports zero initialization when used with parentheses, despite the common misconception that it leaves memory uninitialized.
The above is the detailed content of When Does the `new` Operator Initialize Memory to Zero?. For more information, please follow other related articles on the PHP Chinese website!