如何在 C++ 中使用 new 运算符初始化内存?

How to initialise memory with new operator in C++?(如何在 C++ 中使用 new 运算符初始化内存?)

本文介绍了如何在 C++ 中使用 new 运算符初始化内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始接触 C++,我想养成一些好习惯.如果我刚刚使用 new 运算符分配了一个 int 类型的数组,我如何将它们全部初始化为 0 而不需要自己循环遍历它们?我应该只使用 memset 吗?有没有C++"?怎么做?

I'm just beginning to get into C++ and I want to pick up some good habits. If I have just allocated an array of type int with the new operator, how can I initialise them all to 0 without looping through them all myself? Should I just use memset? Is there a “C++” way to do it?

推荐答案

这是 C++ 的一个令人惊讶的鲜为人知的特性(事实证明还没有人给出这个答案),但它实际上有特殊的值初始化数组的语法:

It's a surprisingly little-known feature of C++ (as evidenced by the fact that no-one has given this as an answer yet), but it actually has special syntax for value-initializing an array:

new int[10]();

请注意,您必须使用空括号——例如,您不能使用 (0) 或其他任何东西(这就是为什么这只对值初始化有用).

Note that you must use the empty parentheses — you cannot, for example, use (0) or anything else (which is why this is only useful for value initialization).

这是 ISO C++03 5.3.4[expr.new]/15 明确允许的,它说:

This is explicitly permitted by ISO C++03 5.3.4[expr.new]/15, which says:

创建 T 类型对象的 new 表达式初始化该对象如下:

A new-expression that creates an object of type T initializes that object as follows:

...

  • 如果 new-initializer 的形式为 (),则该项是值初始化的 (8.5);
  • If the new-initializer is of the form (), the item is value-initialized (8.5);

并且不限制允许的类型,而 (expression-list) 形式受到同一部分中进一步规则的明确限制,因此它不允许数组类型.

and does not restrict the types for which this is allowed, whereas the (expression-list) form is explicitly restricted by further rules in the same section such that it does not allow array types.

这篇关于如何在 C++ 中使用 new 运算符初始化内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 C++ 中使用 new 运算符初始化内存?

基础教程推荐