C++ 自定义Allocator

直接上代码

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

public:
    Allocator()
    {
        // std::cout << "Allocator()" << std::endl;
    }
    Allocator(const Allocator& alloc)
    {
        // std::cout << "Allocator(const Allocator&)" << std::endl;
    }

    ~Allocator()
    {
        // std::cout << "~Allocator()" << std::endl;
    }
    // Allocator& operator=(const Allocator&) = default;

    template <typename _Tp1>
    struct rebind
    {
        typedef Allocator<_Tp1> other;
    };

    pointer address(reference __x) const noexcept
    {
        return std::__addressof(__x);
    }

    const_pointer address(const_reference __x) const noexcept
    {
        return std::__addressof(__x);
    }

    pointer allocate(size_type __n, const void* = static_cast<const void*>(0))
    {
        if (__n > max_size())
            std::__throw_bad_alloc();

        // std::cout << "allocate(" << __n << ")" << std::endl;
        return static_cast<pointer>(::operator new(__n * sizeof(value_type)));
        // return static_cast<pointer>(gMem);
    }

    void deallocate(pointer __p, size_type)
    {
        ::operator delete(__p);
    }

    size_type max_size() const
    {
        // std::cout << "max_size():" << __PTRDIFF_MAX__ << std::endl;
        return size_t(__PTRDIFF_MAX__) / sizeof(value_type);
    }

    template <typename _Up, typename... _Args>
    void construct(_Up* __p, _Args&&... __args) noexcept(std::is_nothrow_constructible<_Up, _Args...>::value)
    {
        // std::cout << "construct(" << __p << ")" << typeid(_Up).name() << std::endl;
        ::new ((void*)__p) _Up(std::forward<_Args>(__args)...);
    }

    template <typename _Up>
    void destroy(_Up* __p) noexcept(std::is_nothrow_destructible<_Up>::value)
    {
        // std::cout << "destroy(" << __p << ")" << typeid(_Up).name() << std::endl;
        __p->~_Up();
    }

    template <typename _Up>
    friend bool operator==(const new_allocator&, const new_allocator<_Up>&) noexcept
    {
        return true;
    }

    template <typename _Up>
    friend bool operator!=(const new_allocator&, const new_allocator<_Up>&) noexcept
    {
        return false;
    }
};

在使用的时候需要注意

1.修改allocate和deallocate函数,替换为自己的创建和回收实现。

2.在针对basic_string使用要注意,basic_string如果字符串小于16字节不会使用分配器,而是使用对象内部预定义的16字节内存空间。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值