C++模板来实现一个通用的内存池.
来源:互联网 发布:王思聪女友雪梨淘宝店 编辑:程序博客网 时间:2024/05/18 20:09
从最简单的入手
1.实现一个固定大小的allocator
//分配固定大小内存块的模板类,内部缓存算法自己实现了,
//我用的是预分配+回收cache链
//即分配时先检查回收链有无数据,无的话每次分配n*size个块,然后返回其中一个,直到该块用完后继续分配
//释放时直接加入回收链即可
//好处是速度够块,但是浪费空间可能就比较大了
template <size_t size> class Fix_Allocator{
void* alloc(size_t size);
void free(void*p);
typedef Fix_Allocator me;
static me Instance;
};
提供一个给host class用的impl template
template <class Host> class new_op{
void* operator new(size_t size);
//........
};
template <
typename Host
>
inline void* new_op<Host>:: operator new(size_t size){
return Fix_Allocator<sizeof(Host)>::Instance.alloc(size);
}
然后所有需要内存池的类继承new_op即可
class cls_usePool:public new_op<cls_usePool>{
.........
};
2.改进
以上方法的不足,大小近似的类不能共享内存池,如sizeof(clsA)==11,sizeof(clsB)==12,
内存池并不能提高程序太多效率.
我用的办法是将所有分配大小对齐到2的冥(这样最大内存占用将会接近原来的一倍,考虑(17,33这样大小的对像很多的情况)
解决方法如下
template <bool flag, typename T, typename U>
struct TypeSelectT
{
private:
template<bool>
struct In
{ typedef T Result; };
template<>
struct In<false>
{ typedef U Result; };
public:
typedef typename In<flag>::Result Result;
};
#define countof(x) (sizeof(x)/sizeof(x[0]))
template <int x,int y>
struct extr{
protected:
template <int x1>
struct imp{
enum {
next=(x1+y-1)/y,
};
enum {Result=1+imp<next>::Result};
};
template <>struct imp<1>{
enum {Result=0};
};
public:
enum {Result=imp<x>::Result};
};
template <int x,int y>
struct pwr{
protected:
template <int y1>
struct imp{
enum{
next=y1-1
};
enum{
Result=x*imp<next>::Result
};
};
template<> struct imp<0>{
enum{
Result=1
};
};
public:
enum{
Result=imp<y>::Result
};
};
template <int size>struct allocIdx{
template <int idx> struct table{
// enum{ }
struct accept{
enum{ Result=0};
};
struct Overflow{
enum{ Result =1};
};
enum {
k
// Result =TypeSelectT< (idx>=0)&&(idx<countof(allocTable)),accept,Overflow>::Result::Result
};
};
};
先用extr算sizeof(cls)最接近2的多少次冥n,然后用pwr计算2的n次冥的值
最后用n查allocidx表得到该大小下,内存块的cache数.
最后将这些值传递给new_op的方法
这样就做到了11 12 13大小的对像全部共享16的allocator,而且是静态绑定的.
- C++模板来实现一个通用的内存池.
- 【C++】通过模板实现一个通用的冒泡排序
- 一个C/C++通用的Makefile模板
- 一个通用纯C队列的实现
- POI实现一个通用的Excel读取模板
- 一个通用的单体模板
- 嵌入式(标准C环境下)下通用的内存池的实现---C文件
- 嵌入式(标准C环境下)下通用的内存池的实现---前言
- 嵌入式(标准C环境下)下通用的内存池的实现---头文件
- 嵌入式(标准C环境下)下通用的内存池的实现---后记(使用)
- 一个.NET通用JSON解析/构建类的实现(c#)
- 一个.NET通用JSON解析/构建类的实现(c#)
- 一个.NET通用JSON解析/构建类的实现(c#)
- c语言实现一个简单的通用动态数组
- 一个通用并发对象池的实现
- 一个通用并发对象池的实现
- 一个通用并发对象池的实现
- 实现一个线程安全的内存池(使用线程私有数据机制TSD来实现)
- win32界面
- 谈谈我对攻读计算机研究生的看法
- IBM Rational Rose 2003 下载
- C++Builder中注册表的操作 (转载)
- 0.11LINUX读核日记(1)
- C++模板来实现一个通用的内存池.
- 8088 汇编速查手册
- C++Builder中注册表的操作 (转载)
- 框架、应用框架
- 测试
- AT & T汇编简介
- 测试
- 手生
- 数学答案(数列、极限、数学归纳法)-[仅供内部参考]