Operator new initializes memory to zero(运算符 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
我读到 new 不会用零初始化内存.但在这里似乎确实如此.它是如何工作的?
I have read that new doesn't initialize memory with zeroes. But here it seems that it does. How does it work?
推荐答案
有两个版本:
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)
回答下面的评论.
嗯...你确定 new unsigned int[5]() 将整数归零吗?
Ehm... are you sure that
new unsigned int[5]()zeroes the integers?
显然是的:
[C++11: 5.3.4/15]:创建类型 T 的对象的 new 表达式将对象初始化如下:如果省略 new-initializer,则对象默认初始化 (8.5);如果未执行初始化,则对象具有不确定的值.否则,new-initializer 将按照 8.5 的初始化规则进行直接初始化.
[C++11: 5.3.4/15]: A new-expression that creates an object of type T initializes that object as follows: If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed, the object has indeterminate value. Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.
#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] << "
"; // If these are zero then it worked as described.
std::cout << wsa[1] << "
"; // If they contain the numbers 1 - 5 then it failed.
std::cout << wsa[2] << "
";
std::cout << wsa[3] << "
";
std::cout << wsa[4] << "
";
}
结果:
> g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.2.0
Thread model: posix
> g++ t.cpp
> ./a.out
0
0
0
0
0
>
这篇关于运算符 new 将内存初始化为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:运算符 new 将内存初始化为零
基础教程推荐
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
