Operator new Initializes Memory to Zero
Despite the general misconception that the new operator does not initialize memory with zeroes, it can indeed accomplish this task under specific conditions.
In C , there are two main scenarios where the new operator performs zero initialization:
Parentheses Initialization:
When new is followed by parentheses and an empty initializer list, such as wsk = new unsigned int();, it explicitly invokes the default constructor of the type. For primitive types like unsigned int, the default constructor initializes the memory to zero.
Parenthesized Array Initialization:
Similar to the previous scenario, using parentheses and an empty initializer list within array declaration, like wsa = new unsigned int[5]();, initializes each element of the array to zero.
In the example code provided, the following lines showcase zero initialization:
wsk2 = new unsigned int(5);
This initializes wsk2 to the value 5.
wsk2 = new unsigned int;
This initializes wsk2 to zero because it uses the parentheses syntax without an initializer list. This behavior applies to both scalars and arrays.
In the second part of the example, the output confirms the zero initialization:
wsk2: 0x928e008 5 wsk2: 0x928e008 0
The first line shows that wsk2 points to the address 0x928e008 and contains the value 5. After deleting wsk2 and creating another one using new unsigned int;, the second line shows that it now points to the same address (0x928e008) but contains zero.
The above is the detailed content of Does the `new` Operator in C Always Initialize Memory to Zero?. For more information, please follow other related articles on the PHP Chinese website!