操作符new将内存初始化为零 [英] Operator new initializes memory to zero
问题描述
有这样的代码:
#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)
在回答下面的注释。 >
In answer to comment below.
Ehm ...您确定新的unsigned int5将整数置零吗?
Ehm... are you sure that new unsigned int5 zeroes the integers?
显然是的:
[C ++ 11:5.3.4 / 15]:new-创建一个类型为T的对象初始化该对象,如下所示:如果省略了new-initializer,则该对象被默认初始化(8.5)。如果未执行初始化,则对象具有不确定的值。否则,根据用于直接初始化的初始化规则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] << "\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";
}
结果:
> 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将内存初始化为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!