Loading

C++分配器Allocator

C++分配器Allocator

分配器用来分配原始的,未经构造的内存,与 new 关键字不同,分配器将内存的分配和释放行为分开。

C++ 中的容器默认使用 std::allocator<T> 来分配内存,它是 C++ 中的默认分配器,其包含在头文件 <memory> 中。 比如 vector 的原型就是:

template<typename _Tp, typename _Alloc = std::allocator<_Tp> > class vector;

此外,你还可以自定义自己的分配器,来控制容器分配内存的行为。

std::allocator<T> 提供 4 个关键函数来管理内存:

函数 作用
allocate 分配未经构造的原始内存
deallocate 释放已经分配的内存
construct 在原始内存上构造对象
destroy 析构对象

std::allocator<T> 的实现中,allocatedeallocate 只是单纯的调用 operator newoperator delete

此外,标准库还为std::allocator<T> 提供了 4 个伴随算法,用来在原始内存上构造对象:

函数 作用
uninitialized_copy(first, last, result) 从 [first,last) 指定的范围拷贝对象到 result 指向的内存
uninitialized_copy_n(first, n, result) 从 [first,first+n) 指定的范围拷贝对象到 result 指向的内存
uninitialized_fill(first, last, x) 在 [first,last) 指定的原始内存上构造对象,对象的初始值都是 x
uninitialized_fill_n(first, n, x) 在 [first,first + n) 指定的原始内存上构造对象,对象的初始值都是 x
posted @ 2022-06-26 22:48  cclemontree  阅读(307)  评论(0)    收藏  举报