C++中的placement new--在指定位置调用某类的构造函数

[size=large]先贴上参考资料的网址:[/size]
1、[url]http://www.builder.com.cn/2008/0104/696370.shtml[/url]
2、[url]http://c.chinaitlab.com/basic/783582_2.html[/url]

[size=large]感觉自己用的话不需要重载new运算符,毕竟都是要分配内存,调用构造函数。。自己做内存管理直接申请一块大内存用placement new创建对象就好了。
另外,明白了delete与delete[] 的区别在于delete[]回收内存前还会逐个调用析构函数,因而对于简单类型等无需析构的两者没啥区别。[/size]

#pragma  once
#include "iostream"
//#include <new.h>

using namespace std;

class A
{
public:
int a;
int* pInt;
A(){
pInt=new int[10];
}


A(int a):a(a){
pInt=new int[10];
}

~A(){
cout<<"A的析构函数!!a="<<a<<";\tpInt="<<(long long)pInt<<endl;
if(pInt!=NULL)
{
delete[] pInt;
pInt=NULL;
}
}


// void* operator new(size_t size)
// {
// cout<<"operator new called"<<endl;;
// return ::operator new(size);
// }

// void* operator new(size_t /*省略名称以防编译器警告*/,void* location=(void*)0){//placement new ,如 new(p) A(3); //p->A::A(3); //必须#include <new>
// cout<<"placement new called"<<endl;
// return location;
// }

};

// void* operator new(size_t size)
// {
// cout<<"global new"<<endl;
// return malloc(size);
// }


void main(){
//A* a = new A();
A a(1);

char* s=new char[sizeof(A)];
A* p = (A*)s;
cout<<"before 'new(p) A(2);' p->a = "<<p->a<<";\tpInt="<<(long long)p->pInt<<endl;
new(p) A(2); //p->A::A(2); //placement new!!!!!!!!!!
cout<<"after 'new(p) A(2);' p->a = "<<p->a<<";\tpInt="<<(long long)p->pInt<<endl;
//p->~A();//需要手动调用析构函数!!!


cout<<"\n****************** test2"<<endl;
char* s2=new char[sizeof(A)];
A* p2 = (A*)s2;
cout<<"before 'p2->A::A(3);' p2->a = "<<p2->a<<";\tpInt="<<(long long)p2->pInt<<endl;
p2->A::A(3);//placement new!!!!!!!!!! 的第二种写法
cout<<"after 'p2->A::A(3);' p2->a = "<<p2->a<<";\tpInt="<<(long long)p2->pInt<<endl;
// p2->~A();


delete[] s;//编译器不知道s中的内容是类A啊,不调用析构函数
delete[] s2;

//测试数组
// cout<<"\n\\\\\\\\\\\\*****测试数组"<<endl;
// A* aa=new A[10];
// delete[] aa;

cout<<"\n****************** 从main函数返回前的最后一句"<<endl;
}


[color=red][size=large]输出如下:[/size][/color]
[img]http://dl.iteye.com/upload/attachment/0076/5596/9e5b559b-edb8-35ab-a3a0-8cb610fd102a.png[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值