#include "stdafx.h"
#include <iostream>
#include <memory>
using namespace std;
/*allocator类和new运算符的一些关于内存的操作
作者:blackmanba
时间:2010年10月6日
*/
class Zoo
{
public:
Zoo()
{
printf("默认构造函数/n");
}
Zoo(string str):m_str(str)
{
printf("有参构造函数/n");
}
Zoo(const Zoo& other)
{
this->m_str = other.m_str;
printf("拷贝构造函数/n");
}
~Zoo()
{
printf("析构函数/n");
}
private:
string m_str;
};
int main()
{
/*定位new的使用,定位new并不分配内存,他只是在已分配的内存的指定位置创建对象*/
Zoo* p = new Zoo[2]; //调用默认构造函数
for (int i=0; i<2; i++)
{
new(p+i)Zoo(i+""); //定位new的使用,调用有参构造函数
new(p+1)Zoo;//定位new的使用,调用默认构造函数
}
delete []p;// 调用析构函数,释放分配的内存
printf("/n");
/*allocator的使用*/
allocator<Zoo> alloc;
Zoo *p1 = alloc.allocate(2);
for (int i=0; i<2; i++)
{
alloc.construct(p1+i, Zoo(i+""));//先创建临时对象Zoo,然后在调用拷贝构造函数创建一个临时对象,然后将临时对象传给construct
}
printf("/n");
for (int i=0; i<2 ;i++)
{
new(p1+i)Zoo(i+"");//直接进行构造
}
printf("/n");
for (int i=0; i<2; i++)
{
alloc.destroy(p1+i);//对用析构函数,但是不释放内存
//上面这句话等价与显示调用析构函数,如下
p1->~Zoo();//显式调用析构函数的效果是使当地清楚对象本身,但并没有释放对象所占的内存,如果需要可以重用该内存
}
alloc.deallocate(p1, 2);//释放内存
printf("/n");
Zoo* p2 = static_cast<Zoo*> (malloc(sizeof(Zoo)*2));//这句话根本不会调用构造函数
free(p2);//不会调用析构函数
}