new[] 是否调用 C++ 中的默认构造函数?

发布于 2024-09-15 18:44:46 字数 422 浏览 3 评论 0原文

当我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

假情假意假温柔 2024-09-22 18:44:46

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

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

new int[size]();

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]();
ゃ人海孤独症 2024-09-22 18:44:46

内置类型没有默认构造函数,尽管它们在某些情况下可以接收默认值。

但在您的情况下, 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 store count int objects, ie. it allocates sizeof<int>*count.

半世蒼涼 2024-09-22 18:44:46

原始类型默认初始化可以通过以下形式完成:

    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++)

Primitive type default initialization could be done by below 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++)
夜深人未静 2024-09-22 18:44:46

int 不是一个类,它是一个内置数据类型,因此不会调用它的构造函数。

int is not a class, it's a built in data type, therefore no constructor is called for it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文