hash_map && allocator

1 hash_map定义在__gnu_cxx下

template<class _Key, class _Tp, class _HashFcn = hash<_Key>,
             class _EqualKey = equal_to<_Key>, class _Alloc = allocator<_Tp> >
          class hash_map;

其中, 简单的 hash<Key>  定义在_gnu_cxx下, 通常自定义Key, 需要实现hash<Key>

equal_to定义在std下, 自定义的Key也需要实现equal_to

 

 

 

2 allocator

默认的是ext/new_allocator。

使用其他allocator时, 如mt_allocator:

using namespace __gnu_cxx;

 

typedef int hash_map_key;
a)  typedef __mt_alloc<hash_map_key, __common_pool_policy<__pool, true> > myhash_alloc;

b)  typedef hash_map<hash_map_key, V, hash<hash_map_key>, std::equal_to<hash_map_key>, myhash_alloc> myhash_map;

 

a 中, __common_pool_policy 的第一个参数是一个模板类, 该模板接收一个bool参数;   第二个参数是个bool;

疑问? hash_map的allocator的value类型为什么不是pair<hash_map_key, V>, 而是 hash_map_key????  那么插入大量对象时, V也需要使用自己的缓存?

 

 

 

 

 

 

 

 

自定义类直接使用allocator

【重载new, 或者把构造函数和析构函数作为外部不可访问成员。 封装allocator的allocate&deallocate】

typedef __mt_alloc<V, __common_pool_policy<__pool, true> > myalloc;
myalloc m;
//--------new operation. get memory && construct

V *p1 = m.allocate(sizeof(V), 0); //这里没有调用V的构造函数。。
std::cout <<"not constructed: " << p1->i <<"," << p1->j <<"/n";
//placement new

//--------delete operation. destruct && free mem----------//

//do some job
//p1->~V()
m.deallocate(p1, sizeof(V));

 

allocator可以处理成与对象相关【vector的内存池方式,相同类型的不同vector对象,其内存池未必是同一个。 】

与类相关【相同类型的对象公用内存池: 把freelist等处理成静态的】;

或者全局的allocator: 所有类对象都共享同一个内存池

你可能感兴趣的:(vector,Class)