在下面的程式碼片段中:
#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; }
預期的結果是記憶體沒有初始化為零,但輸出是:
wsk2: 0x928e008 5 wsk2: 0x928e008 0
看來operator new正在將記憶體初始化為零,但實際上不是。
它是如何運作的:
new 運算子有兩個版本:
wsk = new unsigned int; // default initialized (ie nothing happens) wsk = new unsigned int(); // zero initialized (ie set to 0)
預設值初始化不會初始化內存,而值初始化不會初始化內存,而零初始化則將記憶體設為零。
它也適用於陣列:
wsa = new unsigned int[5]; // default initialized (ie nothing happens) wsa = new unsigned int[5](); // zero initialized (ie all elements set to 0)
要確認記憶體實際上已清除,我們可以將新的版面與已知的記憶體一起使用:
#include <new> #include <iostream> int main() { unsigned int wsa[5] = {1,2,3,4,5}; // Use placement new (to use a know piece of memory). // In the way described above. // 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"; }
此程式碼的輸出是:
0 0 0 0 0
這證實了記憶體確實被運算子new的零初始化版本清零了。
以上是C 中「new unsigned int」是否將記憶體初始化為零?的詳細內容。更多資訊請關注PHP中文網其他相關文章!