有没有更好的方法来初始化C ++中分配的数组? [英] Is there a better way to initialize an allocated array in C++?

查看:49
本文介绍了有没有更好的方法来初始化C ++中分配的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用另一种(也许更短)的方式写这个?有没有更好的方法可以在C ++中初始化分配的数组?

How to write this in another (perhaps shorter) way? Is there a better way to initialize an allocated array in C++?

int main(void) {
   int* a;
   a = new int[10];
   for (int i=0; i < 10; ++i) a[i] = 0;
}

推荐答案

 int *a =new int[10](); // Value initialization

ISO C ++第8.5/5节

要对T类型的对象进行值初始化,则意味着:

To value-initialize an object of type T means:

-如果T是具有用户声明的构造函数(12.1)的类类型(第9节),则调用T的默认构造函数(如果T没有可访问的默认构造函数,则初始化格式不正确);

— if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

-如果T是没有用户声明的构造函数的非联合类类型,则T的每个非静态数据成员和基类组件都将被值初始化;

— if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;

-如果T是数组类型,则每个元素都将被值初始化;

— if T is an array type, then each element is value-initialized;

否则,对象将初始化为零

要了解术语零初始化值初始化默认初始化之间的差异,请阅读

For differences between the terms zero initialization, value initialization and default initialization, read this

这篇关于有没有更好的方法来初始化C ++中分配的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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