为什么当构造函数称为5次时,攻击函数仅一次称为一次?
我正在尝试了解有关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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用
delete [] a
来删除分配了new []
的数组。如果这样做,您会看到正确的输出:You need to use
delete[] a
to delete an array of things allocated withnew[]
. If you do that, you'll see the correct output: