share_ptr指向的对象的析构动作在创建的时候被捕获

share_ptr智能指针能够记录其实际的指向对象的类型,并正确的析构该对象。
所以使用share_ptr来管理的对象不需要虚析构函数

示例代码

#include <iostream>
#include <memory>
using namespace std;

class base{
public:
        ~base(){cout << "in ~base()" << endl;}
};

class derive : public base
{
public:
        ~derive(){cout << "In ~derive()" << endl;}

};


int main()
{
        base* p =new derive;
        delete p;
        cout << "=============================" <<endl;
        {
                shared_ptr<base> ptr(new derive);
        }
        while(1);
        return 0;
}

运行结果

[lhx@lhx-master share_ptr]$ ./a.out 
in ~base()
=============================
In ~derive()
in ~base()

原文地址:https://www.cnblogs.com/DXGG-Bond/p/14684318.html