设计一个简单地内存分配器(空间分配器)

     ~~~~     前面我们简单地看了关于allocator的一些信息,这里我们写一个简单地内存分配器,我就是直接模拟stl里面的写了.
前面一章写了哪些变量是必须的,这里就不重复写了,直接贴代码:
之前博客地址C++ 分配器 allocator

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

namespace xxxx{

    template <class _Tp>
    class test_allocator{
    public:
        typedef _Tp         value_type;    
        typedef _Tp*        pointer;
        typedef const _Tp*  const_pointer;
        typedef _Tp&        reference;
        typedef const _Tp&  const_reference;
        typedef size_t      size_type;
        typedef ptrdiff_t   difference_type;


        template<class _Tp1>
        struct rebind{
            typedef test_allocator<_Tp1> other;
        };

        test_allocator() { }

        test_allocator(const test_allocator&) { }

        template<typename _Tp1>
	    test_allocator(const test_allocator<_Tp1>&) { }

        ~test_allocator(){ }

        //hint used for Locality, ref.[auslern], p189
        pointer allocate(size_type _n, const_pointer hint = 0){
            return static_cast<value_type*>(::operator new(_n * sizeof(value_type)));
        }

        void deallocate(pointer _p, size_type n){
            ::operator delete(_p);
        }
              
        void construct(pointer __p, const _Tp& __val) {
            ::new((void *)__p) _Tp(__val); 
        }

        void destroy(pointer __p) {
            __p->~_Tp(); 
        }

        pointer address(reference _x){
            return (pointer)&_x;
        }

        const_pointer const_address(const_reference _x){
            return (const_pointer)&_x;
        }

        //#define UINT_MAX	0xFFFFFFFF
        size_type max_size()const {
            return size_type(UINT_MAX/sizeof(value_type));
        }
    };
}


using namespace xxxx;

int main(){
    int _ia[5] = {0, 1, 2, 3, 4};
    int i = 0;
    vector<int, test_allocator<int> > _iv(_ia, _ia + 5);
    for(i = 0; i < _iv.size(); i++){
        cout << _iv[i] << endl;
    }
    cout << endl;
    return 1;
}

编译运行:

qilimi@qilimi-desktop:~/test$ vim main1.cpp
qilimi@qilimi-desktop:~/test$ g++ -o test main1.cpp -std=c++11
qilimi@qilimi-desktop:~/test$ ./test
0
1
2
3
4

qilimi@qilimi-desktop:~/test$

     ~~~~     上面就是我实现的一个简单的空间分配器,只是简单的封装了new和delete,以及调用构造函数和析构函数,而如果我们平时使用的时候,对于申请空间小的容器,我们就需要实现内存池的功能,而内存池就是一次性申请足够量的空间,当容器来申请的时候在之前申请的空间中分配一块出去,对于容器可能没有什么区别但是可以减少系统内存碎片。

你可能感兴趣的:(程序基础,C++,stl)