结论:当父类存在virtual函数时,则需要实现虚析构函数。
直接上代码:
#include<iostream> #include<memory> class AAA { public: AAA() { printf("AAA 构造 ... \n"); } //virtual ~AAA() { printf("AAA 析构 ... \n"); } virtual void SayOk() = 0; }; class aaa :public AAA { public: aaa() { printf("aaa 构造 ... \n"); } ~aaa() { printf("aaa 析构 ... \n"); } virtual void SayOk() { printf("aaa SayOk ... \n"); } }; void test() { //aaa aa; if (1) { std::shared_ptr<AAA> sp = std::make_shared<aaa>(); sp->SayOk(); sp = nullptr; } printf("-------------- 分隔线 -------------- \n"); if (1) { AAA * pp = new aaa(); pp->SayOk(); delete pp; pp = nullptr; } } int main() { test(); return 0; }
如上,假如AAA不实现虚析构函数,则通过new出来的对象,被析构时,会调用不到子类的析构。
父类声明了虚析构,则能够正确调用子类的析构。
标签:aaa,virtual,析构,printf,AAA,虚析构 From: https://www.cnblogs.com/xcywt/p/17899679.html