【std::allocator】
标准库中包含一个名为allocator的类,允许我们将分配和初始化分离。使用allocator通常会提供更好的性能和更灵活的内存管理能力。
标准库allocator类定义在头文件memory中,它帮助我们将内存分配和对象构造分离开来。它提供一种类型感知的内存分配方法,它分配的内存是原始的、未构造的。
allocator支持的操作,如下:
下面是一段标准用法:
int test_allocator_1() { std::allocator<std::string> alloc; // 可以分配string的allocator对象 int n{ 5 }; auto const p = alloc.allocate(n); // 分配n个未初始化的string auto q = p; // q指向最后构造的元素之后的位置 alloc.construct(q++); // *q为空字符串 alloc.construct(q++, 10, 'c'); // *q为cccccccccc alloc.construct(q++, "hi"); // *q为hi std::cout << *p << std::endl; // 正确:使用string的输出运算符 //std::cout << *q << std::endl; // 灾难:q指向未构造的内存 std::cout << p[0] << std::endl; std::cout << p[1] << std::endl; std::cout << p[2] << std::endl; while (q != p) { alloc.destroy(--q); // 释放我们真正构造的string } alloc.deallocate(p, n); return 0; }
参考:
1、https://blog.csdn.net/fengbingchun/article/details/78943527
2、