C++ Primer阅读笔记--allocator类的使用
1--allocator类的使用背景
new 在分配内存时具有一定的局限性,其将内存分配和对象构造组合在一起;当分配一大块内存时,一般希望可以在内存上按需构造对象,这时需要将内存分配和对象构造分离,而定义在头文件 memory 的 allocator 类可以帮助我们将内存分配和对象构造分离开来;
2--allocator类的基本用法
① allocator<T> a 用于定义一个名为 a 的 allocator 对象,其可以为类型为T的对象分配内存;
② a.allocate(n) 用于分配一段原始的、未构造的内存,保存 n 个类型为 T 的对象;
③ a.deallocate(p, n) 用于释放从 T* 指针 p 中地址开始的内存,该内存保存了 n 个类型为 T 的对象;n 必须是 p 创建时所要求的大小,在调用 deallocate 之前必须对创建的对象调用 destroy();
④ a.construct(p, args) 用于在 p 指向的内存中构造一个对象;
⑤ a.destroy(p) 用于对 p 指向的对象执行析构函数;
#include <iostream>
#include <string>
#include <memory>int main(int arc, char *argv[]){std::allocator<std::string> alloc; // 定义对象int n = 20;auto const p = alloc.allocate(n); // 分配n个string的内存auto q = p;alloc.construct(q++); // *q 为空字符串alloc.construct(q++, 10, 'c'); // *q 为ccccccccccalloc.construct(q++, "hi"); // *q 为hiauto i = p;while(i != q){std::cout << *i << std::endl;alloc.destroy(i);i++;}alloc.deallocate(p, n);return 0;
}// 输出结果
//
// cccccccccc
// hi
3--allocator类的拷贝填充
① uninitialized_copy(b, e, b2) 用于将迭代器 b 到 e 范围内元素拷贝到迭代器 b2 指定的未构造的原始内存中;
② uninitialized_copy_n(b, n, b2) 用于从迭代器 b 开始,拷贝 n 个元素到 b2 开始的内存中;
③ uninitialized_fill(b, e, t) 用于在迭代器 b 和 e 指定的范围内创建对象,对象的值均为 t 的拷贝;
④ uninitialized_fill_n(b, n, t) 用于从迭代器 b 开始创建 n 个对象,对象的值均为 t 的拷贝;
#include <iostream>
#include <string>
#include <memory>int main(int arc, char *argv[]){std::allocator<std::string> alloc1; int n = 20;auto const p = alloc1.allocate(n);auto q = p;alloc1.construct(q++); // *q 为空字符串alloc1.construct(q++, 10, 'c'); // *q 为ccccccccccalloc1.construct(q++, "hi"); // *q 为histd::allocator<std::string> alloc2;auto const p2 = alloc2.allocate(2 * n);std::uninitialized_copy(p, q, p2);std::uninitialized_fill_n(q, 7, "aaa");auto i = p;while(i != p + 10){std::cout << *i << std::endl;i++;}return 0;
}// 输出结果
//
// cccccccccc
// hi
// aaa
// aaa
// aaa
// aaa
// aaa
// aaa
// aaa