new[] 是否调用 C++ 中的默认构造函数?
当我使用 new[] 创建类数组时:
int count = 10;
A *arr = new A[count];
我看到它调用了 A
count
次默认构造函数。结果,arr
拥有 count
个已初始化的 A
类型对象。 但是如果我使用同样的东西来构造一个 int 数组:
int *arr2 = new int[count];
它没有初始化。尽管 int 的默认构造函数将其值分配给 0
,但所有值都类似于 -842150451
。
为什么会有如此不同的行为?是否仅为内置类型调用默认构造函数?
When I use new[] to create an array of my classes:
int count = 10;
A *arr = new A[count];
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];
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请参阅接受的答案 到 非常相似问题。当您使用
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
只是在内存中分配足够的空间来存储count
int
对象,即。它分配sizeof*count
。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 storecount
int
objects, ie. it allocatessizeof<int>*count
.原始类型默认初始化可以通过以下形式完成:
Primitive type default initialization could be done by below forms:
int
不是一个类,它是一个内置数据类型,因此不会调用它的构造函数。int
is not a class, it's a built in data type, therefore no constructor is called for it.