再谈定位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();