C++自动析构时的顺序

自动析构时是先析构后构造的.

//普通(非模板)类的成员模板
class DebugDelete{
public:
    DebugDelete(ostream &s = cerr) :os(s){}
    template <typename T>void operator()(T*p)const
    {
        os << "deleting unique_ptr  " <<typeid(T).name() <<endl;
        delete p;
    }
private:
    ostream &os;
};
void demo_general_class_tempalte_member()
{
    double *p = new double;
    DebugDelete d;
    d(p);//d调用DebugDelet::operator()(double*),释放p
    int* ip = new int;
    //在一个临时DebugDelete 对象上调用operator()(int*)
    DebugDelete()(ip);
    //实例化DebugDelete::opeartor()<int>(int*)const
    unique_ptr<int, DebugDelete>p2(new int, DebugDelete());
    //实例化DebugDelete::opeartor()<string>(string*)const
    unique_ptr<string, DebugDelete>sp(new string, DebugDelete());

}

这里输出

deleting unique_ptr  double
deleting unique_ptr  int
deleting unique_ptr  class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
deleting unique_ptr  int


可以看到,主动析构的正常进行.
函数结束后自动析构的,先创建了int后创建了string,但是先析构了string

class B
{
public:
    virtual ~B(){ cout << "delete B" << endl; }
};

class D :B
{
public:
    virtual ~D() override{ cout << "delete D" << endl; }
};

void demo_delete()
{
    D d;
}

输出

delete D

delete B

这里构造时是先构造基类,再构造派生类.但是在析构时是先析构了子类,再析构了基类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值