本文章转自网易博客:小萝卜头
http://mmjinglin.blog.163.com/blog/static/20486210201262411360/16
//placenew2.cpp---new,placement new,no delete #include<iostream> #include<string> #include<new>//放置语法中需调用 using namespace std; const int BUF=512;
class JustTesting { private: string words; int number; char c1; 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() { char *buffer=new char[BUF]; // get a block of memory
//new操作符创建一个512字节的内存缓冲区 JustTesting *pc1,*pc2;
pc1=new (buffer) JustTesting; //place object in buffer pc2=new JustTesting("Heap1",20); //place object on heap
cout<<"Memory block addresses:\n"<<"buffer:" <<(void*)buffer<<", heap:"<<pc2<<endl; cout<<"Memory contents:\n"; cout<<pc1<<": "; pc1->Show(); cout<<pc2<<": "; pc2->Show();
JustTesting *pc3,*pc4; //fix placement new location pc3=new (buffer+sizeof(JustTesting)) JustTesting("Better Idea",6);
//自行管理内存缓存区内存单元,为pc1和pc3提供位于缓存区的不同地址 pc4=new JustTesting("Heap2",10);
cout<<"Memory contents:\n"; cout<<pc3<<": "; pc3->Show(); cout<<pc4<<": "; pc4->Show();
delete pc2; //free Heap1 delete pc4; //free Heap2 //explicitly destory placement new objects pc3->~JustTesting(); //destory object pointed to by pc3 pc1->~JustTesting(); //destory object pointed to by pc4、
//使用指向对象的指针,显示调用析构函数销毁对象 delete [] buffer; //释放使用常规new操作符分配的整个内存块,但他没有为布局new操作符在该内存块中创建的对象调用析构函数,因此需要显示调用析构函数 cout<<"Done \n"; // cout<<sizeof(string); //cout<<sizeof(JustTesting); return 0; }
pc1->~JustTesting(); //destory object pointed to by pc4