stl源码——内存配置及构造

配置及构造

// 调用底层alloc
    template <class T, class A = __default_alloc>
    class simpleAlloc
    {
    public:
        using value_type = T;
        using pointer = T*;
        using const_pointer = const T*;
        using reference = T&;
        using const_reference = const T&;
        using size_type = size_t;
        using difference_type = ptrdiff_t;

    public :
    // 分配空间的静态函数
        static T* allocate();
        static T* allocate(size_t n);
        static void deallocate(T* ptr);
        static void deallocate(T* ptr, size_t n);

        static void construct(T* ptr);
        static void construct(T* ptr, const T& value);

        static void destory(T* ptr);
        static void destory(T* first, T* last);
    };

实现

    // 静态方法
    template <class T, class A>
    T* simpleAlloc<T, A>::allocate()
    {
        return reinterpret_cast<T*>(A::allocate(sizeof(T)));
    }

    template <class T, class A>
    T* simpleAlloc<T, A>::allocate(size_t n)
    {
        if (n == 0)
        {
            return 0;
        }
        return reinterpret_cast<T*>(A::allocate(sizeof(T) * n));
    }

    template <class T, class A>
    void simpleAlloc<T, A>::deallocate(T* ptr)
    {
        A::deallocate(reinterpret_cast<void*>(ptr), sizeof(T));
    }

    template <class T, class A>
    void simpleAlloc<T, A>::deallocate(T* ptr, size_t n)
    {
        if (n == 0)
        {
            return;
        }
        A::deallocate(reinterpret_cast<void*>(ptr), sizeof(T) * n);
    }

    template <class T, class A>
    void simpleAlloc<T, A>::construct(T* ptr)
    {
        new (ptr) T();
    }

    template <class T, class A>
    void simpleAlloc<T, A>::construct(T* ptr, const T& value)
    {
        new (ptr) T(value);
    }

    template <class T, class A>
    void simpleAlloc<T, A>::destory(T* ptr)
    {
        ptr->~T();
    }
    
    template <class T, class A>
    void simpleAlloc<T, A>::destory(T* first, T* last)
    {
        for (; first != last; first++)
        {
            first->~T();
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值