allocator代表一种特定内存模型,并提供一种抽象概念,将对内存的索求最终转变为对内存的直接调用。
可以自己实现一个分配器。
allocator:使内存分配和构造分离,提高性能;销毁内存和析构分离:提高性能,内存可重用;在需要对象的时候再进行构造
例子:
new string[100],意味着要执行100次string类的默认构造函数,哪怕后面的用不到!同样析构也会需要执行100次!
可以通过allocator来实现分离,代码如下:
#include<iostream>
#include<string>
#include<vector>
#include<memory>
using namespace std;
int main()
{
allocator<string> nAllocator;
string* const p = nAllocator.allocate(10);
string* q = p;
nAllocator.construct(q++);
nAllocator.construct(q++,5,'A');
nAllocator.construct(q++,"ABC");
while (q != p)
{
nAllocator.destroy(--q);
}
nAllocator.deallocate(p, 10);
cout << "----------------------------" << endl;
vector<string> vec = { "1","12","23","34&