Home > Backend Development > C++ > When Does the `new` Operator Initialize Memory to Zero?

When Does the `new` Operator Initialize Memory to Zero?

DDD
Release: 2024-12-19 00:56:18
Original
429 people have browsed it

When Does the `new` Operator Initialize Memory to Zero?

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;
}
Copy after login

Outputs:

wsk2: 0x928e008 5
wsk2: 0x928e008 0
Copy after login

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:

  • wsk = new unsigned int; // Default initialized (ie nothing happens)
  • wsk = new unsigned int(); // Zero initialized (ie set to 0)

This behavior also applies to arrays:

  • wsa = new unsigned int[5]; // Default initialized (ie nothing happens)
  • wsa = new unsigned int[5](); // Zero initialized (ie all elements set to 0)

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";
}
Copy after login

Outputs:

0
0
0
0
0
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template