Unable to use custom allocator with allocate_shared/make_shared

前端 未结 2 829
离开以前
离开以前 2021-01-04 23:55

In my C++11 program, I use shared_ptr for some objects which are actively created and deleted. It so happened that standard allocator with operat

2条回答
  •  臣服心动
    2021-01-05 00:34

    Like this.. You need it templated, you need the rebind and the types and the allocate and deallocate members. It is also nice to have the operators..

    #include 
    
    template
    struct Allocator
    {
        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;
    
        template
        struct rebind {typedef Allocator other;};
    
        Allocator() throw() {};
        Allocator(const Allocator& other) throw() {};
    
        template
        Allocator(const Allocator& other) throw() {};
    
        template
        Allocator& operator = (const Allocator& other) { return *this; }
        Allocator& operator = (const Allocator& other) { return *this; }
        ~Allocator() {}
    
        pointer allocate(size_type n, const void* hint = 0)
        {
            return static_cast(::operator new(n * sizeof(T)));
        }
    
        void deallocate(T* ptr, size_type n)
        {
            ::operator delete(ptr);
        }
    };
    
    template 
    inline bool operator == (const Allocator&, const Allocator&)
    {
        return true;
    }
    
    template 
    inline bool operator != (const Allocator& a, const Allocator& b)
    {
        return !(a == b);
    }
    
    
    int main()
    {
        std::allocate_shared>(Allocator(), 0);
    }
    

    At the very LEAST, an allocator could look like:

    template
    struct Allocator
    {
        typedef T value_type;
    
        Allocator() noexcept {};
    
        template
        Allocator(const Allocator& other) throw() {};
    
        T* allocate(std::size_t n, const void* hint = 0)
        {
            return static_cast(::operator new(n * sizeof(T)));
        }
    
        void deallocate(T* ptr, size_type n)
        {
            ::operator delete(ptr);
        }
    };
    
    template 
    inline bool operator == (const Allocator&, const Allocator&)
    {
        return true;
    }
    
    template 
    inline bool operator != (const Allocator& a, const Allocator& b)
    {
        return !(a == b);
    }
    

    This will also work for allocate_shared.. However, being the type of person I am, I prefer to have all the functions.. Even the ones not required/used by said container/function.

提交回复
热议问题