一.new
new 动态开辟内存的时候一共分为两个步骤
(1)new调用了内部封装了的operator new 函数(开辟空间)
(2)new 调用构造函数在开辟的空间上构造对象
二.delete
(1)调用析构函数清理对象
(2)释放空间调用operator delete
三.
(1)new表达式,可以允许程序猿要求将对象创建在已经被分配好的内存中
(2)
定位new表达式的常见形式
new(address) type;
new(address) type(initializers);
new(address) type[size];
new(address) type[size]{braced initializer list};
(3)
定位new表达式调用 void *operator new(size_t, void *); 分配内存
//将A*pA=new A[10];
//delete [] pA;另类实现
#include<iostream>
using namespace std;
class A
{
public:
A(int a):_a(a)
,_p(new int)
{
cout<<"A()"<<endl;
}
~A()
{
cout<<"~A()"<<endl;
delete _p;
}
private:
int _a;
int *_p;
};
int main()
{
//定位new 表达式
A *pA=(A*)operator new[](sizeof(A)+4);
*(int*)pA=10;
int i=0;
//整形指针加1一次偏移一个字节,但结构体A大小为8时一次要偏移8个字节
A* pstart=(A*)((int*)pA+1);
for(i=0;i<10;i++)
{
//对已有空间进行对象的构造
new ((A*)(pstart+i))A(i);
}
int count=*((int*)pstart-1);
for(i=0;i<count;i++)
{
pstart[i].~A();
}
operator delete[]((int*)pstart-1);
system("pause");
return 0;
}
本文出自 “1” 博客,请务必保留此出处http://10808695.blog.51cto.com/10798695/1748585
原文:http://10808695.blog.51cto.com/10798695/1748585