[英]Does new[] call default constructor in C++?
When I use new[] to create an array of my classes:当我使用 new[] 创建我的类数组时:
int count = 10;
A *arr = new A[count];
I see that it calls a default constructor of A
count
times.我看到它调用了
A
count
次的默认构造函数。 As a result arr
has count
initialized objects of type A
.结果
arr
有count
个A
类型的初始化对象。 But if I use the same thing to construct an int array:但是如果我使用同样的东西来构造一个 int 数组:
int *arr2 = new int[count];
it is not initialized.它没有被初始化。 All values are something like
-842150451
though default constructor of int assignes its value to 0
.尽管 int 的默认构造函数将其值分配给
0
,但所有值都类似于-842150451
。
Why is there so different behavior?为什么会有如此不同的行为? Does a default constructor not called only for built-in types?
默认构造函数不只为内置类型调用吗?
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. 当您使用
new[]
每个元素均由默认构造函数初始化,但类型为内置类型时除外。 Built-in types are left unitialized by default. 内置类型默认情况下保持统一。
To have built-in type array default-initialized use 内置类型数组默认初始化使用
new int[size]();
Built-in types don't have a default constructor even though they can in some cases receive a default value. 内置类型没有默认构造函数,即使它们在某些情况下可以接收默认值也是如此。
But in your case, new
just allocates enough space in memory to store count
int
objects, ie. 但是在您的情况下,
new
只是在内存中分配了足够的空间来存储count
int
对象,即。 it allocates sizeof<int>*count
. 它分配
sizeof<int>*count
。
Primitive type default initialization could be done by below forms:原始类型默认初始化可以通过以下 forms 完成:
int* x = new int[5]; // gv gv gv gv gv (gv - garbage value)
int* x = new int[5](); // 0 0 0 0 0
int* x = new int[5]{}; // 0 0 0 0 0 (Modern C++)
int* x = new int[5]{1,2,3}; // 1 2 3 0 0 (Modern C++)
int
不是类,它是内置数据类型,因此没有为其构造函数的调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.