new[] 在 C++ 中调用默认构造函数吗? [英] Does new[] call default constructor in C++?

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

问题描述

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

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

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

我看到它调用了 A count 次的默认构造函数.结果 arrcount 个初始化 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 的默认构造函数将其值分配给 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?

推荐答案

参见 接受的答案 一个非常相似的问题.当您使用 new[] 时,每个元素都由默认构造函数初始化,除非类型是内置类型.默认情况下,内置类型保持单元化.

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]();

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

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