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将构造函数 析构函数剥离,手动进行控制