随笔-91  评论-137  文章-0  trackbacks-0
作为一个山寨的STL,那么不得不提的是其中的allocator(空间配置器)。顾名思义,它是负责空间分配用的,下面代码十分简单,仅对C函数malloc和free进行了薄薄的一层封装,同时给定了自定义函数free_handler用于在空间分配时候由于内存被占满了而导致的分配失败。

这里值得注意的是:这个释放函数的函数指针应该是由调用方来负责指定,并且它仅有一个参数表明至少需要释放多少字节的内存。

下面来看代码,代码非常简单,应此这里就不逐一展开说明了。
#ifndef _QLANGUAGE_LIBRARY_ALLOC_H_
#define _QLANGUAGE_LIBRARY_ALLOC_H_

#if 0
#include 
<new>
#define __THROW_BAD_ALLOC throw std::bad_alloc
#elif !defined(__THROW_BAD_ALLOC)
#include 
<iostream>
#define __THROW_BAD_ALLOC std::cerr << "out of memory" << std::endl; exit(1)
#endif

namespace QLanguage
{
    
namespace Library
    
{
        template 
<typename T>
        
class allocator
        
{
        
public:
            allocator()
            
{
            }


            allocator(
const allocator<T>&)
            
{
            }


            
static T* allocate()
            
{
                
const size_t size = sizeof(T);
                T
* result = (T*)malloc(size);
                
while(result == nullptr)
                
{
                    
if(free_handler) free_handler(size);
                    
else __THROW_BAD_ALLOC;
                    result 
= (T*)malloc(size);
                }

                
return result;
            }


            
static T* allocate(const size_t& n)
            
{
                
const size_t size = n * sizeof(T);
                
if(size <= 0throw "bad allocate size";
                T
* result = (T*)malloc(size);
                
while(result == nullptr)
                
{
                    
if(free_handler) free_handler(size);
                    
else __THROW_BAD_ALLOC;
                    result 
= (T*)malloc(size);
                }

                
return result;
            }


            
static void deallocate(T* p)
            
{
                free(p);
            }


            
static void deallocate(T* p, const size_t&)
            
{
                free(p);
            }


            
static T* reallocate(T* p, const size_t& n)
            
{
                
const size_t size = n * sizeof(T);
                
if(size <= 0throw "bad reallocate size";
                T
* result = (T*)realloc(p, size);
                
while(result == nullptr)
                
{
                    
if(free_handler) free_handler(size);
                    
else __THROW_BAD_ALLOC;
                    result 
= (T*)realloc(p, size);
                }

                
return result;
            }

        
public:
            
static void(*free_handler)(const size_t&);

            
static void set_handler(void(*h)(const size_t&))
            
{
                free_handler 
= h;
            }

        }
;

        template 
<typename T>
        typename 
void (*allocator<T>::free_handler)(const size_t&= nullptr;
    }

}


#endif

完整代码请到http://qlanguage.codeplex.com/下载
posted on 2012-05-20 21:45 lwch 阅读(1844) 评论(0)  编辑 收藏 引用 所属分类: STL

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理