有关类对象的NEW布局操作符
#include <iostream>
#include <string>
#include <new> //包含布局操作符原型
using namespace std;
const int BUF=512;
class JustTesting
{
private:
string words;
int number;
public:
JustTesting (const string & s="just testing",int n=0)
{words=s;number=n;cout<<words<<" constructed\n";}
~JustTesting(){cout<<words<<" destroyed\n";}
void show()const {cout<<words<<","<<number<<endl;}
};
int main(void)
{
char * buffer=new char[BUF];
JustTesting *pc1,*pc2;
pc1=new (buffer) JustTesting;
pc2=new JustTesting("heap1",20);
cout<<"mem block addr:\n"<<"buffer: "<<(void*)buffer<<" heap: "<<pc2<<endl;
cout<<"Mem contents:\n";
cout<<pc1<<": ";
pc1->show();
cout<<pc2<<": ";
pc2->show();
JustTesting *pc3,*pc4;
pc3=new (buffer+sizeof(JustTesting)) JustTesting("bad idea",6);
pc4=new JustTesting("heap2",10);
cout<<"Mem contents:\n";
cout<<pc3<<": ";
pc3->show();
cout<<pc4<<": ";
pc4->show();
delete pc2;
delete pc4;
pc3->~JustTesting();//显式调用析构函数
pc1->~JustTesting();//显式调用析构函数
delete [] buffer;
cout<<"done\n";
return 0;
}


浙公网安备 33010602011771号