首頁 >後端開發 >C++ >C 中「new unsigned int」是否將記憶體初始化為零?

C 中「new unsigned int」是否將記憶體初始化為零?

Barbara Streisand
Barbara Streisand原創
2024-12-08 13:45:12340瀏覽

Does `new unsigned int` Initialize Memory to Zero in C  ?

operator new 將記憶體初始化為零

在下面的程式碼片段中:

#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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn