运算符 new 将内存初始化为零 [英] Operator new initializes memory to zero

查看:22
本文介绍了运算符 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 将内存初始化为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆