New的放置语法

本文章转自网易博客:小萝卜头

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=new (buffer) JustTesting;   放置语法: 就是从buffer为首地址分配一段内存给pc1,这段内存是已经预先开辟的。
 
      delete [] buffer;   使用deletet释放buffer中常规new操作符分配的整个内存块时,没有为布局new操作符在该内存块中创建的对象pc1,pc3调用析构函数,因此需要显示调用析构函数。
 pc3->~JustTesting();       //destory object pointed to by pc3
 pc1->~JustTesting();       //destory object pointed to by pc4
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值