实现自己的STL配置器allocator

本文介绍了如何实现自己的STL配置器,包括一个简单的allocator实现和测试。同时,详细讲解了new的三种使用方式:plain new、nothrow new和placement new,强调了placement new的主要用途和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现自己的STL配置器

STL所有数据都存储在容器之中,而容器需要配置空间以置放资料,所以配置器就是完成这一个任务的。

以下是它的一些接口

allocator::value_type
//类型,如int

allocator::pointer
//指针,如int *

allocator::const_pointer

allocator::reference
//引用, 如int &

allocator::const_reference


allocator::size_type
//大小,如size_t

allocator::difference_type
//difference_type是一种常用的迭代器型别,用来表示两个迭代器之间的距离,因此它也可以用来表示一个容器的最大容量,因为对于连续空间的容器而言,头尾之间的距离就是其最大容量。

allocator::rebind
//rebind实现了对不同类型使用同一种内存分配策略的要求

allocator::allocator()
//默认的构造函数

allocator::allocator(const allocator&)
//复制构造函数
    
template <class U>allocator::allocator(const allocator<U>&)
//泛化复制构造函数
    
allocator::~allocator()
//析构函数
pointer allocator::address(reference x) const
//返回某个对象的地址,a.address(x) 相当于 &x
    
const_pointer allocator::address(const_reference x) const
//返回某个对象的地址,a.address(x) 相当于 &x

pointer allocator::allocate(size_type n, const void* = 0)
//分配可以存储n个T对象的空间。第二个参数是个提示,实现上可能会用它来增进区域性(locality),或完全忽略之
    
void allocator::deallocator(pointer p, size_type n)
//清除空间
    
size_type allocator::max_size() const
//返回可以配置的最大值
    
void allocator::construct(pointer p, const T& x
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值