operator new 将内存初始化为零
在下面的代码片段中:
1 2 3 4 5 6 7 8 9 10 | # 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;
}
|
登录后复制
预期的结果是内存没有初始化为零,但输出是:
1 2 | wsk2: 0x928e008 5
wsk2: 0x928e008 0
|
登录后复制
看来operator new正在将内存初始化为零,但实际上不是。
它是如何工作的:
new 运算符有两个版本:
1 2 | wsk = new unsigned int;
wsk = new unsigned int();
|
登录后复制
默认值初始化不会初始化内存,而零初始化则将内存设置为零。
它也适用于数组:
1 2 | wsa = new unsigned int[5];
wsa = new unsigned int[5]();
|
登录后复制
要确认内存实际上已清零,我们可以将新的布局与已知的一块内存一起使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # 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" ;
std::cout << wsa[1] << "\n" ;
std::cout << wsa[2] << "\n" ;
std::cout << wsa[3] << "\n" ;
std::cout << wsa[4] << "\n" ;
}
|
登录后复制
此代码的输出是:
这证实了内存确实被运算符 new 的零初始化版本清零了。
以上是C 中'new unsigned int”是否将内存初始化为零?的详细内容。更多信息请关注PHP中文网其他相关文章!