zoukankan      html  css  js  c++  java
  • 标准库Allocator的简易实现(二)

    自己实现Allocator并不难,其实只需要改变allocate和deallocate,来实现自己的内存分配策略。

    下面是一个std::allocator的模拟实现

    #ifndef ALLOCATOR_HPP
    #define ALLOCATOR_HPP
    
    #include <stddef.h>
    #include <limits>
    
    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;
    
        //Allocator::rebind<T2>::other
        template <typename V>
        struct rebind
        {
            typedef Allocator<V> other;
        };
    
        pointer address(reference value) const { return &value; }
        const_pointer address(const_reference value) const { return &value; }
    
        Allocator() throw() {   }
        Allocator(const Allocator &) throw() {  }
        //不同类型的allcator可以相互复制
        template <typename V> Allocator(const Allocator<V> &other) { } 
        ~Allocator() throw() {  }
    
        //最多可以分配的数目
        size_type max_size() const throw()
        { return std::numeric_limits<size_type>::max() / sizeof(T); }
    
        //分配内存,返回该类型的指针
        pointer allocate(size_type num)
        { return (pointer)(::operator new(num * sizeof(T))); }
    
        //执行构造函数,构建一个对象
        void construct(pointer p, const T &value)
        { new ((void*)p) T(value); }
    
        //销毁对象
        void destroy(pointer p)
        { p->~T(); }
    
        //释放内存
        void deallocate(pointer p, size_type num)
        { ::operator delete((void *)p); }
    };
    
    //这两个运算符不需要friend声明
    template <typename T, typename V>
    bool operator==(const Allocator<T> &, const Allocator<V> &) throw()
    { return true; }
    
    template <typename T, typename V>
    bool operator!=(const Allocator<T> &, const Allocator<V> &) throw()
    { return false; }
    
    
    #endif

    这里注意rebind的实现,如果需要使用Test的分配器分配其他类型,就可以这样:

    Allocator<Test>::rebind<Test2>::other alloc;

    测试代码如下:

    #include "Allocator.hpp"
    #include <string>
    #include <vector>
    using namespace std;
    
    
    int main(int argc, char const *argv[])
    {
        vector<string, Allocator<string> > vec(10, "haha");
    
        vec.push_back("foo");
        vec.push_back("bar");
    
        //Allocator<Test>::rebind<Test2>::other alloc;
    
        return 0;
    }
  • 相关阅读:
    求求你规范下你的代码风格
    为啥用ip不可以访问知乎,而百度却可以?
    漫画:htts是如何保证一台主机把数据安全发给另一台主机
    如何从亿量级中判断一个数是否存在?
    广播路由算法 :我是如何优雅着把悄悄话带给其他人的
    什么?你不知道0.0.0.0和255.255.255.255这两个地址是干嘛的?
    一篇文章带你学会Linux三剑客之一:awk
    你真的了解 i++, ++i 和 i+++++i 以及 i+++i++ 吗?
    通俗易懂讲解TCP流量控制机制,了解一下
    一文读懂拥塞控制
  • 原文地址:https://www.cnblogs.com/inevermore/p/4004261.html
Copyright © 2011-2022 走看看