在跟着B站某视频学C++学到多态时敲代码,发现一个问题,先上代码(使用的是Visual Studio)
#include<iostream>
using namespace std;
#include<string>
class cpu {
public:
virtual void calculate() = 0;
};
class card {
public:
virtual void display() = 0;
};
class memory {
public:
virtual void store() = 0;
};
class IntelCPU :public cpu {
public:
void calculate() {
cout << "使用IntelCPU计算" << endl;
}
~IntelCPU() {
cout << "调用IntelCPU析构函数" << endl;
}
};
class IntelCARD :public card {
public:
void display() {
cout << "使用IntelCARD显示" << endl;
}
~IntelCARD() {
cout << "调用IntelCARD析构函数" << endl;
}
};
class IntelMEM :public memory {
void store() {
cout << "使用IntelMEM存储" << endl;
}
};
class computer {
public:
computer(cpu* cp, card* ca, memory* me) {
a = cp;
b = ca;
c = me;
}
void work() {
a->calculate();
b->display();
c->store();
}
~computer() {
if (a != NULL) {
delete a;
a = NULL;
}
if (b != NULL) {
delete b;
b = NULL;
}
if (c != NULL) {
delete c;
c = NULL;
}
cout << "调用computer析构函数" << endl;
}
private:
cpu* a;
card* b;
memory* c;
};
void dowork(computer* com) {
com->work();
}
int main() {
IntelCPU* cp= new IntelCPU;
IntelCARD* ca = new IntelCARD;
IntelMEM* me = new IntelMEM;
computer* a = new computer(cp, ca, me);
dowork(a);
delete a;
}
结果:
在main函数中,delete a
后cp开辟的空间确实被释放了(在computer a的析构函数中释放),但此时却没有调用IntelCPU的析构函数:
class IntelCPU :public cpu {
public:
void calculate() {
cout << "使用IntelCPU计算" << endl;
}
~IntelCPU() {
cout << "调用IntelCPU析构函数" << endl;
}
};
而如果删去delete a
,而加上delete cp
,则会调用该析构函数:
但是如果同时写上:delete a
和delete cp
,此时编译器则会报错:
我估计原因是因为重复释放了内存,也就证明前面cp开辟的空间确实被释放了,但此时在computer
中的析构函数:
~computer() {
if (a != NULL) {
delete a;
a = NULL;
}
if (b != NULL) {
delete b;
b = NULL;
}
if (c != NULL) {
delete c;
c = NULL;
}
cout << "调用computer析构函数" << endl;
}
中的delete a
(就是delete cp,,写的没注意名称重复的问题。。)却并不会调用IntelCPU的析构函数。
想问问各位对此有什么看法?
(重点不是在cp已经被释放,而是没有调用析构函数,如果我IntelCPI* cp时,cp中有指针开辟了堆上数据,那不是这部分数据就不能释放而泄漏了吗?
ps:视频中还教了一种写法,即:computer* a = new computer(new IntelCPU,new IntelCARD,new IntelMEM);
,此时就完全不能调用各个Intel的析构函数了,因为在main中连类型名都没有);