您的位置:首页 > 编程语言 > C语言/C++

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

2017-08-17 12:06 459 查看
再谈定位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 pc
4000
1 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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: