是否新的[]调用默认的构造函数在C ++? [英] Does new[] call default constructor in C++?

查看:130
本文介绍了是否新的[]调用默认的构造函数在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用新的[]创建我的类的数组:

When I use new[] to create an array of my classes:

int count = 10;
A *arr = new A[count];

我看到它调用 A 的默认构造函数计数倍。结果改编计数类型的初始化的对象 A
但是,如果使用同样的事情来构建一个int数组:

I see that it calls a default constructor of A count times. As a result arr has count initialized objects of type A. But if I use the same thing to construct an int array:

int *arr2 = new int[count];

这是未初始化。所有数值都是像 -842150451 虽然为int的默认构造函数assignes其值设置为 0

it is not initialized. All values are something like -842150451 though default constructor of int assignes its value to 0.

为什么会出现如此不同的行为呢?难道一个默认的构造函数不仅没有呼吁内建类型?

Why is there so different behavior? Does a default constructor not called only for built-in types?

推荐答案

请参阅the接受的答案以<一个href=\"http://stackoverflow.com/questions/2468203/how-can-i-make-new-default-initialize-the-array-of-primitive-types\">a非常类似的问题。当您使用新[] 的每个元素用默认的构造函数除了当类型是初始化内置类型。内置类型留在默认情况下未初始化。

See the accepted answer to a very similar question. When you use new[] each element is initialized by the default constructor except when the type is a built-in type. Built-in types are left unitialized by default.

要具有内置类型的数组默认初始化使用

To have built-in type array default-initialized use

new int[size]();

这篇关于是否新的[]调用默认的构造函数在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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