《STL源码剖析》chapter2空间配置器allocator
2014-04-27 01:59 youxin 阅读(519) 评论(0) 编辑 收藏 举报为什么不说allocator是内存配置器而说是空间配置器,因为空间不一定是内存,也可以是磁盘或其他辅助介质。是的,你可以写一个allocator,直接向硬盘取空间。sgi stl提供的配置器,配置的对象是内存。
stl中allocator用法参考以前的http://www.cnblogs.com/youxin/archive/2012/06/07/2540170.html。
书中jj allocator类
#ifndef _JJALLOC #define _JJALLOC #include<new> //for placement new #include<cstddef> //for ptrdiff_t ,size_t #include<cstdlib> //for exit() #include<climits> //for UINX_MAX #include<iostream> //for cerr namespace JJ { template<class T> inline T* _allocate(ptrdiff_t size,T*) { set_new_handler(0); T* tmp=(T*)(::operator new((size_t)(size*sizeof(T)))); if(tmp==0) { cerr<<"out of memory"<<endl; exit(1); } return tmp; } template<class T> inline void _deallocate(T* buffer) { ::operator delete(buffer); } template<class T1,class T2> inline void _construct(T1* p,const T2& value) { new(p) T1(value);//placement new,invoke constuctor of t1 } template<class T> inline void _destroy(T* ptr) { ptr->~T(); } template<class T> class allocator{ public: typedef T value_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; //rebind allocator of type U template<class U> struct rebind{ typedef allocator<U> other; }; //需要加上以下2个函数,windows的编译器用到了allocator不同类型的拷贝, allocator() { return ; } template <class U> allocator(const allocator<U>& c ) { } //hint user for locality,第2个参数是个提示,实现上可能会利用它来增进区域性(locality),或完全忽略之 pointer allocate(size_type n,const void* hint=0) { return _allocate((difference_type)n,(pointer)0); } void deallocate(pointer p,size_type n) { _deallocate(p); } void construct(pointer p,const T& value) { _construct(p,value); } void destroy(pointer p) { _destroy(p); } pointer address(reference x) { return (pointer)&x;} const_pointer const_address(const_reference x) { return (const_pointer)&x;} size_type max_size() const{ return size_type(UINT_MAX/sizeof(T)); } }; }//#end of namespace JJ #endif
#include"2jjalloc.h" #include<vector> #include<iostream> using namespace std; int main() { int ia[5]={0,1,2,3,4}; unsigned int i; vector<int,JJ::allocator<int> > iv(ia,ia+5); for(i=0;i<iv.size();i++) cout<<iv[i]<<ends; cout<<endl; }
这个allocator只能有限程序带票PJ STL,
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
2012-04-27 快速排序
2012-04-27 求 最大公约数和最小公倍数
2012-04-27 迭代法 详解