string allocator

之前客户报内存频繁malloc, free

用了内存池重载class new,但是string使用没搞定allocator,导致使用了char数组workaround, 最近发现很简单

typedef std::basic_string<char, std::char_traits<char>, mlallocator<char>> mlstring;

只要重写mlallocator就行:

#include "ml_mt_allocator.h"

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

    mlallocator()noexcept{}
    mlallocator(const mlallocator&)noexcept{}
    template <typename U>
    mlallocator(const mlallocator<U>&)noexcept{}
    ~mlallocator()noexcept{}

    // bigger than 4G fail
    T* allocate(std::size_t num, const void* hint = 0)
    {
        return get_mt_allocator<T>().allocate(num*sizeof(T));
    }

    void deallocate(T* p, std::size_t num)
    {
        get_mt_allocator<T>().deallocate(p, num);
    }

    T* address(T& value)const
    {
        return &value;
    }

    const T* address(const T& value)const
    {
        return &value;

 }

    std::size_t max_size()const noexcept
    {
       return std::numeric_limits<std::size_t>::max()/sizeof(T);
    }

    void construct(T* p, const T& value)
    {
        ::new((void*)p)T(value);
    }

    void destroy(T* p)
    {
        p->~T();
    }

    template <typename U>
    struct rebind
    {
        typedef mlallocator<U> other;
    };
};

template <typename T1, typename T2>
bool operator == (const mlallocator<T1>&, const mlallocator<T2>&)noexcept
{
    return true;
}

template <typename T1, typename T2>
bool operator != (const mlallocator<T1>&, const mlallocator<T2>&)noexcept
{
    return false;
}
 

"ml_mt_allocator.h"即是多线程内存池的ext gnu版本封装

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值