为什么当构造函数称为5次时,攻击函数仅一次称为一次?

发布于 2025-02-13 02:35:03 字数 569 浏览 1 评论 0原文

我正在尝试了解有关C ++的更多信息,在此代码中,我正在分配一个A的数组(在这种情况下为5),我了解5 A将被分配...因此编译器将使Consenter称为约束5倍,但是,如果删除该数组仅一次称驱动器一次,所以我的问题是,为什么只有在具有5个A时才将其称为Destructor一次,他不应该将destructor称为5次?

我有此代码:

#include <iostream>
using namespace std;

class A {
public:
    A() { std::cout << "IM in C'tor" << std::endl; };
    ~A() { std::cout << "IM in De'tor" << std::endl; }
};


int main()

{
    A* a = new A[5];
    delete a;  // ingone the errors,the important thing is calling the 
                 C'tor and D'tor` 
    return 0;
}

I'm trying to learn more about C++ ,int this code I'm allocating an array of A's (5 in this case), what I understand that 5 A's will be allocated ...so the compiler will call 5 times the constructer , but in case of deleting that array it calls the destructor one time only ,so my question is why does it call the destructor one time only when it has 5 A's , shouldn't he call the destructor 5 times??

I have this code :

#include <iostream>
using namespace std;

class A {
public:
    A() { std::cout << "IM in C'tor" << std::endl; };
    ~A() { std::cout << "IM in De'tor" << std::endl; }
};


int main()

{
    A* a = new A[5];
    delete a;  // ingone the errors,the important thing is calling the 
                 C'tor and D'tor` 
    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

拧巴小姐 2025-02-20 02:35:03

您需要使用delete [] a来删除分配了new []的数组。如果这样做,您会看到正确的输出:

IM in C'tor
IM in C'tor
IM in C'tor
IM in C'tor
IM in C'tor
IM in De'tor
IM in De'tor
IM in De'tor
IM in De'tor
IM in De'tor

You need to use delete[] a to delete an array of things allocated with new[]. If you do that, you'll see the correct output:

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