C++ 虚析构函数
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ 虚析构函数相关的知识,希望对你有一定的参考价值。
代码如下:
#include <iostream>
using namespace std;
class Base {
public:
Base() {
cout << "Base" << endl;
}
~Base() {
cout << "Base destructor" << endl;
}
};
class Derived : public Base {
public:
Derived() {
cout << "Derived rush" << endl;
p = new int(0);
}
~Derived() {
cout << "Derived destructor" << endl;
delete p;
}
private:
int *p;
};
void fun(Base *b) {
delete b;
}
int main() {
Base *b = new Derived();
fun(b);//输出:Base destructor
}
结果表明: 通过基类指针只能调用基类的析构函数, 这就造成派生类对象中动态分布的内存空间将不会得到释放, 从而造成“ 内存泄漏”。
代码如下:
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base( ) {
cout << "Base destructor" << endl;
}
};
class Derived: public Base {
public:
Derived( ) {
p = new int(0) ;
}
~Derived( ) {
cout << "Derived destructor" << endl;
delete p;
}
private:
int *p;
};
void fun(Base *b) {
delete b;
}
int main( ) {
Base *b = new Derived( );
fun(b);
return 0;
}
以上是关于C++ 虚析构函数的主要内容,如果未能解决你的问题,请参考以下文章