Chinaunix首页 | 论坛 | 博客
  • 博客访问: 255210
  • 博文数量: 21
  • 博客积分: 1263
  • 博客等级: 准尉
  • 技术积分: 697
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-24 00:05
个人简介

专注于Answers Ranking, Answer Monitor和log处理。

文章分类
文章存档

2014年(5)

2012年(16)

分类: C/C++

2012-04-09 14:25:09

SGI里面提供了一个简单的符合STL标准的内存分配器template class allocator,但是SGI里面没有文件用它分配空间,都是用的,这个allocator是对operator new 和 operator delete的简单封装。下面看它的源文件内容:

点击(此处)折叠或打开

  1. template <class T>
  2. inline T* allocate(ptrdiff_t size, T*)
  3. {
  4.     set_new_handler(0);
  5.     T* tmp = (T*)(::operator new((size_t)(size * sizeof(T))));
  6.     if (tmp == 0)
  7.     {
  8.         cerr << "out of memory" << endl;
  9.         exit(1);
  10.     }
  11.     return tmp;
  12. }


  13. template <class T>
  14. inline void deallocate(T* buffer)
  15. {
  16.     ::operator delete(buffer);
  17. }

  18. template <class T>
  19. class allocator
  20. {
  21. public:
  22.     typedef T value_type;
  23.     typedef T* pointer;
  24.     typedef const T* const_pointer;
  25.     typedef T& reference;
  26.     typedef const T& const_reference;
  27.     typedef size_t size_type;
  28.     typedef ptrdiff_t difference_type;
  29.     pointer allocate(size_type n)
  30.     {
  31.         return ::allocate((difference_type)n, (pointer)0);
  32.     }
  33.     void deallocate(pointer p) { ::deallocate(p); }
  34.     pointer address(reference x) { return (pointer)&x; }
  35.     const_pointer const_address(const_reference x)
  36.     {
  37.         return (const_pointer)&x;
  38.     }
  39.     size_type init_page_size()
  40.     {
  41.         return max(size_type(1), size_type(4096 / sizeof(T)));
  42.     }
  43.     size_type max_size() const
  44.     {
  45.         return max(size_type(1), size_type(UINT_MAX / sizeof(T)));
  46.     }
  47. };

  48. class allocator<void>
  49. {
  50. public:
  51.     typedef void* pointer;
  52. };
在文件的最原后特化了void类型,对它不做任何处理。

唯一想不明白地方就是在template <class T> inline T* allocate(ptrdiff_t size, T*
) 中的第一个参数类型是ptrdiff_t,它是在stddef.h中定义的,主要是计算两个指针之间的距离,但它是有符号的。虽然在new的时候转换成size_t类型了。。。




阅读(1683) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~