#include<iostream>
#include<memory>
#include<cstring>
using namespace std;
class obj{
public:
int a;
char str[20];
obj(int n,const char* p){
a=n;
strcpy(str,p);
// cout<<"construct"<<endl;
}
~obj(){
//cout<<"delete"<<endl;
}
};
int main(){
typedef unsigned char byte; //定义数据类型
byte *buffer=new byte[sizeof(int)+sizeof(byte)*100]; //建立内存缓冲区
cout<<"before new:"<<endl; //打印当前内存布局
for(int i=0;i<100;i++){
cout<<(int)buffer[i]<<" ";
}
cout<<endl;
obj *a=new(buffer)obj(1,"daf"); //在offset=0的地方新建一个sizeof(obj)的对象
obj *b=new(buffer+sizeof(obj))obj(10,"sdfasdf"); //在offset=sizeof(obj)的地方新建一个sizeof(obj)的对象,如果不加上offset,那么将会覆盖前一个内存的地址
//综上所述,实际上placement new只是在已经申请好的内存上调用了类的构造函数,并不涉及到内存的申请
cout<<"after new:"<<endl;
for(int i=0;i<100;i++){
cout<<(int)buffer[i]<<" ";
}
cout<<endl;
cout<<a->str<<endl<<b->str<<endl; //显示测试的值
a->~obj();
b->~obj(); //这些对象需要手动管理,那么就需要手动释放内存
delete[] buffer; //释放缓冲区
return 0;
}