STL源码解析-02配置器-03自定义配置器

#include <vector>
#include <new>
#include <cstddef>
#include <cstdlib>
#include <climits>
#include <iostream>
 
********************************************
 * c++中的new操作其实进行了三部:
 * 1、分配内存空间  ===>    pointer = operator new(size_t),只管分配内存。
 * 2、调用构造函数  ===>    new(pointer) T(value),这是placement new操作,对一块内存地址初始化,堆栈均可以。
 * 3、返回指针地址  ===>    return pointer
 * 在调用new时,会自动调用构造函数,在STL的allocator中,把new进行了拆分。
 * allocate,deallocate完成对内存地址的分配,不管构造。
 * construct,deconstruct完成内存地址的构造。
 * *******************************************
 
namespace myspace{
 
template <class T>
inline T* _allocate(size_t n, T*)
{
    //set_new_handler(0);
    T* tmp = (T*)::operator new(n*sizeof(T));
    if (tmp == NULL)
    {
        std::cerr << "out of memery.\n";
        exit(1);
    }
    return tmp;
}
 
template <class T>
inline void _deallocate(T* p)
{
    ::operator delete(p);
}
 
template <class T1, class T2>
inline void _construct(T1* p, const T2& value)
{
    new (p) T1(value);
}
 
template <class T>
inline void _destroy(T *p)
{
    p->~T();
}
 
template <class T>
class myallocator{
    public:
        typedef T value_type;
        typedef T* pointer;
        typedef const T* const_pointer;
        typedef T& reference;
        typedef const T& const_reference;
        typedef size_t size_type;
        typedef ptrdiff_t difference_type;
 
 
        pointer allocate(size_t n)
        {
            return _allocate(n,(pointer)0);
        }
 
        void deallocate(T* p)
        {
            _deallocate(p);
        }
 
        void constuct(T* p, const T& value)
        {
            _construct(p, value);
        }
 
        void destroy(T* p)
        {
            _destroy(p);
        }
 
        pointer address(reference a)
        {
            return (pointer)&a;
        }
        
        const_pointer const_address(const_reference ca)
        {
            return (const_pointer)&ca;
        }
        
        size_type max_size()const
        {
            return size_type(UINT_MAX/sizeof(T));
        }
 
};
}
 
 
int main()
{
    using namespace myspace;
    int ia[5] = {0,1,2,3,4};
    //自定义的allocater只能自己用了,放到vector中时,不符合STL的规范。。
    unsigned int i;
    std::vector<int,std::allocator<int> > iv(ia,ia+5);
    for (i=0; i<iv.size(); i++)
        std::cout << iv[i] << std::endl;
    std::cout << std::endl;
    return 0;
}
posted @ 2011-12-02 14:59  magicdog  阅读(160)  评论(0)    收藏  举报