/*
基类析构函数[是虚函数]:
指向派生类的基类指针在析构的时候
[普通指针,shared_ptr,unique_ptr][都会先调用派生类的析构函数,然后再调用基类的析构函数]
*/
/*
基类析构函数[不是虚函数]:
指向派生类的基类指针在析构的时候
[普通指针,unique_ptr][只会调用基类的析构函数,不会调用派生类的析构函数]
[shared_ptr][会先调用派生类的析构函数,然后再调用基类的析构函数]
*/
#include <iostream>
#include <string>
#include <memory>
class BaseA
{
int data;
std::string msg;
public:
BaseA() {
msg="BaseA message";
}
/*
~BaseA() {
std::cout<<__FUNCTION__<<std::endl;
}
*/
virtual ~BaseA() {
std::cout<<__FUNCTION__<<std::endl;
}
virtual void show_msg() {
std::cout<<msg<<std::endl;
}
};
class DeriveA:public BaseA
{
int data;
std::string msg;
public:
DeriveA() {
msg="DeriveA message";
}
~DeriveA() {
std::cout<<__FUNCTION__<<std::endl;
}
void show_msg() {
std::cout<<msg<<std::endl;
}
};
void UsePrivateFunc() {
{
std::cout<<"ptr BaseA:"<<std::endl;
BaseA* ptr_BaseA(new DeriveA());
ptr_BaseA->show_msg();
delete ptr_BaseA;
}
std::cout<<"\n";
{
std::cout<<"unique_ptr BaseA:"<<std::endl;
std::unique_ptr<BaseA> uptr_BaseA(new DeriveA());
uptr_BaseA->show_msg();
}
std::cout<<"\n";
{
std::cout<<"shared_ptr BaseA:"<<std::endl;
std::shared_ptr<BaseA> sptr_BaseA(new DeriveA());
sptr_BaseA->show_msg();
}
}
int main(int argc,char* argv[])
{
UsePrivateFunc();
return 0;
}
析构函数是虚函数的输出结果:
![1430944-20190613205843960-1856916566.png](https://i-blog.csdnimg.cn/blog_migrate/36e23228ca749f8cec7ff347fa93570f.png)
析构函数不是虚函数的输出结果:
![1430944-20190613205915123-429516597.png](https://i-blog.csdnimg.cn/blog_migrate/17185906f72202a52c46445a2d646798.png)