实现自定义的 STL allocator

STL allocator 的注释讲解请见:http://blog.csdn.net/lifesider/archive/2011/06/06/6527776.aspx

 

这里实现的自定义allocator是继承自std::allocator,因为两者有公共部分,对于完全重写的allocator,下面的内容就不用读了。

 

上源码

#include <memory> template<class T> class user_defined_allocator : public std::allocator<T> { public: typedef std::allocator<T> base_type; // 必须要重新定义,否则容器如 list, set, map 使用时作用域只能到达 std::allocator template<class Other> struct rebind { typedef user_defined_allocator<Other> other; }; // 构造函数必须实现 user_defined_allocator() {} user_defined_allocator(user_defined_allocator<T> const&) {} user_defined_allocator<T>& operator=(user_defined_allocator<T> const&) { return (*this); } // idiom: Coercion by Member Template template<class Other> user_defined_allocator(user_defined_allocator<Other> const&) {} // idiom: Coercion by Member Template template<class Other> user_defined_allocator<T>& operator=(user_defined_allocator<Other> const&) { return (*this); } // 内存的分配与释放可以实现为自定义的算法,替换函数体即可 pointer allocate(size_type count) { return (base_type::allocate(count)); } void deallocate(pointer ptr, size_type count) { base_type::deallocate(ptr, count); } };

 

附注:

采用继承自std::allocator的方法,发现需要自定义实现的接口很少,代码量因此也少很多

(1)rebind 的作用

(2)Coercion by Member Template 惯用法的使用,同时构造函数需要显示实现

(3)allocate和deallocate接口的实现

 

你可能感兴趣的:(算法,list,user)