《STL源码分析》学习笔记 — 空间配置器 — 规范与设计


STL运用的角度而言,空间配置器总是隐藏在容器的背后,是不需要介绍的东西。但从实现的角度来说,空间配置器是需要首先掌握的东西,因为整个 STL的操作对象都存放在容器之中,而容器一定要配置空间以置放资源。

一、空间配置器的标准接口

根据C++标准(C++17),allocator的接口和类型包括:

// 构造和析构 c++20 中下面函数应为constexpr
allocator::allocator(const allocator& __a)
allocator::allocator(allocator&& __a)
template<typename _Tp1>
allocator::allocator(const allocator<_Tp1>&) // 将一个配置器赋值给另一个配置器
template<typename _Tp1>
allocator::allocator(allocator<_Tp1>&&)

// 操作符
allocator::opearator=(const allocator& a)
allocator::opearator=(allocator&& a)
allocator::opearator==(const allocator& a)
allocator::opearator!=(const allocator& a)
template<typename _Tp1>
allocator::opearator==(const allocator<_Tp1>& b)
template<typename _Tp1>
allocator::opearator!=(const allocator<_Tp1>& b)

// 内置类型
(可选)allocator::pointer
(可选)allocator::const_pointer
(可选)allocator::void_pointer
(可选)allocator::const_void_pointer
allocator::value_type
(可选)allocator::size_type
(可选)allocator::difference_type
(可选)template<typename _Tp1>
(可选)allocator::template rebind<_Tp1>::other // 嵌套类模板,拥有唯一成员other,那是一个typedef,代表allocator<U>
	
// 存储和生命周期操作
allocator::pointer allocator::allocate(size_type __n) // 配置空间,足以存储n个对象
(可选)allocator::pointer allocator::allocate(size_type __n, const_void_pointer __hint) // 同上,第二个参数用于locality
void allocator::deallocate(pointer __p, size_type __n) // 归还配置的空间,第二个参数用于设置空间大小,现在编译器基本上不使用此参数
(可选)template<typename _Up, typename... _Args>
(可选)void allocator::construct(_Up* __p, _Args&&... __args) // 等同于 new((void*)p) _Up(_Args)
(可选)template<typename _Up>
(可选)void allocator::destroy(_Up* __p) // 等同于 p->~_Up()
(可选)allocator::size_type allocator::max_size() // 返回可成功配置的最大空间

// 对容器操作的影响
(可选)allocator::select_on_container_copy_construction() // 当使用当前配置器的容器发生拷贝时,提供一个默认构造的配置器或当前配置器的拷贝
(可选)allocator::propagate_on_container_copy_assignment // std::true_type 表示上述函数中新容器的配置器为当前配置器的拷贝 
(可选)allocator::propagate_on_container_move_assignment // 与上面类似,为当前容器的移动构造
(可选)allocator::propagate_on_container_swap // std::true_type 当两个容器内容发生交换时,配置器也应该相互交换

// 其他
(可选)allocator::is_always_equal // std::true_type 表示两个配置器总是相同的

// 指针操作,用于内置类型 pointer 和 const_pointer。在C++98中,指针相关的操作函数为 address,现标准中无此要求
*p // allocator::pointer&
*q // allocator::const_pointer&
p->m // 返回 T::m
q->m // 返回 T::m
static_cast<allocator::pointer>(w) // allocator::pointer
static_cast<allocator::const_pointer>(w) // allocator::const_pointer
std::pointer_traits<allocator::pointer>::pointer_to(r) // allocator::pointer

allocate有一个版本支持参数 hint,C++手册中对这个参数的解释为:

The pointer hint may be used to provide locality of reference: the allocator,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值