首页 >后端开发 >C++ >C 中'new unsigned int”是否将内存初始化为零?

C 中'new unsigned int”是否将内存初始化为零?

Barbara Streisand
Barbara Streisand原创
2024-12-08 13:45:12369浏览

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