new[] 在 C++ 中调用默认构造函数吗?
当我使用 new[] 创建我的类的数组时:
When I use new[] to create an array of my classes:
int count = 10;
A *arr = new A[count];
我看到它调用了 A
count
次的默认构造函数.结果 arr
有 count
个初始化 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]();