操作符new将内存初始化为零

编程入门 行业动态 更新时间:2024-10-19 21:27:48
本文介绍了操作符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)

在回答下面的注释。 >

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将内存初始化为零

本文发布于:2023-10-09 05:59:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474902.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   为零   内存   操作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!