12.2.2 allocator类
allocator类将分配内存空间、调用构造函数、调用析构函数、释放内存空间这4部分操作分开,全部交给程序员来执行,不像new和delete
#include <iostream>
#include <string>int main()
{const int n = 10;std::allocator<std::string> alloc; // 定义一个用于分配string的allocator的对象std::string* const p = alloc.allocate(n); // 分配n个未初始化的string的内存,没有调用string的构造函数std::string* q = p;while (q != p + n) { // p + n相当于p[n],即数组最后一个元素的下一个位置alloc.construct(q, 10, 'a'); // 通过q为每个string调用构造函数,构造函数参数由alloc.construct传递std::cout << "construct: " << * q << std::endl;q++; // q最终会指向最后一个string的下一个位置}while (q != p) {q--;std::cout << "destory: " << *q << std::endl;alloc.destroy(q); // 对q指向的string进行析构}alloc.deallocate(p, n); // 释放内存空间,p必须是先前调用allocate时返回的指针,n必须是创建时allocate填入的数量
}