c++ primer plus阅读笔记12---手动调用析构函数

再谈定位new运算符
我们来看代码:

#include <iostream>
#include <string>
#include <new>
using namespace std;
const int BUF=512;
class JustTestting
{
private:
    string words;
    int number;
public:
    JustTestting(const string &s="Just Testing",int n=0)
    {
        words=s;
        number=n;
        cout<<words<<" constructed\n";
    }
    ~JustTestting()
    {
        cout<<words<<" destoryed\n";
    }

    void Show()const
    {
        cout<<words<<","<<number<<endl;
    }
};

int main()
{
    char *buffer=new char[BUF];

    JustTestting *pc1,*pc2;
    pc1=new(buffer)JustTestting;  //pc1在堆上buffer处
    pc2=new JustTestting("Heap1",20);//pc2在堆上

    cout<<"Memory block address\n"<<"buffer:"<<(void *)buffer<<" Heap:"<<pc2<<endl;
    cout<<"Memory contents:\n";
    cout<<pc1<<":";
    pc1->Show();

    cout<<pc2<<":";
    pc2->Show();

    JustTestting *pc3,*pc4;
    pc3=new(buffer)JustTestting("Bad Idea",6);//pc3在堆上buffer处
    pc4=new JustTestting("Heap2",10);  //pc4在堆上
    cout<<"Memory contents:\n";
    cout<<pc3<<":";
    pc3->Show();
    cout<<pc4<<":";
    pc4->Show();
    //pc1-> ~JustTestting();  delete pc1 pc3将会出错,这里需要手动调用pc1的析构函数
    //pc3-> ~JustTestting(); 


    delete pc2;     
    delete pc4;
    delete []buffer;
    cout<<"done\n";
    return  0;


}

上边的代码中,pc1和pc3都在堆上申请的buffer中,当调用delete []buffer时,会将buffer处的内存全部释放,但是delete []buffer并不知道里边还有个对象,所以不会调用该对象的析构函数,为了调用其析构函数,必须手动调用,pc1-> ~JustTestting();

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值