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

2023-07-19C/C++开发问题
2

本文介绍了如何在 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 运算符初始化内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6