测试类的析构函数

#include "thing.h"

void function(Thing t) {
    Thing lt(106);//函数结束时 调用析构 
    Thing* tp1 = new Thing(107);
    Thing* tp2 = new Thing(108);// 不会调用析构
    delete tp1;
}

int main() {
    Thing t1(101), t2(102); // 在main 函数结束时 调用析构
    Thing* tp1 = new Thing(103); 
    function(t1);// 其中t1 在function 结束时调用析构
    {  /* nested block/scope */
        Thing t3(104);// 该作用域结束时 调用析构
        Thing* tp = new Thing(105);// 不会调用析构 
    }
    delete tp1;
    return 0;
}
#ifndef THING_H_
#define THING_H_

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

class Thing {
 public:
    Thing(int n) : m_Num(n) {
        
    }
    ~Thing() {
        cout << "destructor called: " 
             << m_Num << endl;
    }
    
 private:
    string m_String;
    int m_Num;
};
#endif
运行结果
destructor called: 107
destructor called: 106
destructor called: 101
destructor called: 104
destructor called: 103
destructor called: 102
destructor called: 101
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值