如何用C ++中的新操作符初始化内存? [英] How to initialise memory with new operator in C++?

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

问题描述

我刚刚开始进入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 default-initializing an array (well, technically, it's called "value-initialize" in the Standard):

new int[10]();

请注意,您必须使用空括号,使用(0)或任何其他表达式(这是为什么这只有用于默认初始化)。

Note that you must use the empty parentheses - you cannot, for example, use (0) or any other expression (which is why this is only useful for default 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-expression按如下方式初始化该对象:

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 ++中的新操作符初始化内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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