C++ allocators将构造函数,析构函数与分配内存解耦

allocators分配器的作用就是将分配内存与构造函数,析构函数脱离,提高运行效率减少成本。new和delete操作符把内存空间的分配回收与对象的构建销毁紧紧关联在一起。

#include <iostream>
#include <memory>
#include <allocators>
using namespace std;

class Student{
private:
	int a;

public:

	Student(){
	  cout << "default constructer" << endl;
	}

	~Student(){
	  cout << "delete" << endl;
	}

	Student(int x) : a(x){ 
		cout << "constructer" << endl;
	}

	void show(){
	  cout << a << endl;
	}

};




void main1(){
  
  //Student* p = new Student[10];
  //delete[] p;
 
  //匿名对象立刻调用构造然后释放
  //Student();

  //将分配内存与构造析构进行分离  减少成本提高效率
  allocator<Student> allocator;
  Student* stu = allocator.allocate(1);
  //调用构造函数
  //通过匿名对象调用拷贝构造函数
  allocator.construct(stu,Student(10));

  stu->show();

  //释放内容 调用析构
  allocator.destroy(stu);  
  //释放内存
  allocator.deallocate(stu,1);

  cin.get();
}


void main(){

   allocator<Student> alloca;
   Student* parray = alloca.allocate(3);
   alloca.construct(parray,Student(3));
   alloca.construct(parray+1,Student(30));
   alloca.construct(parray+2,Student(333));
   parray->show();
   (parray+1)->show();
   (parray+2)->show();
   alloca.destroy(parray);
   alloca.destroy(parray+1);
   alloca.deallocate(parray,3);
   cin.get();
}


  allocator.construct(stu,Student(10));

这句话对通过Student(10)的匿名对象调用Student的拷贝构造函数进行初始化

这样allocator将构造函数 析构函数剥离,手动进行控制

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值