Since C++11 provides std::allocator_traits to simplify the use of custom allocator,
the minimum requirement of a custom allocator should be like this:

template <typename Tp> 
class SimpleAllocator 
{ 
    public: 
    typedef Tp value_type; 

    template <typename T> 
    struct rebind { typedef SimpleAllocator<T> other; };

    SimpleAllocator() {}

    template <typename T> SimpleAllocator(const SimpleAllocator<T>& other) {}

    Tp* allocate(std::size_t n)
    {
        // do the custom allocate here
    }
    void deallocate(Tp* p, std::size_t n)
    {
        // custom deallocate here
    }
}; 

(This is copied from open-std.org) (I modified some format)

However when I compile this with a std::vector<int, SimpleAllocator<int>>, using VS2012,
the compiler wants me to provide the construct function,
so I am forced to implement addional void construct(Tp* p, const Tp& val)
(and void destroy(pointer p), of course).

Why is that? What am I missing? Or it's because VS2012 didnt provide full support?

Thanks!

有帮助吗?

解决方案

Your version of allocator is perfectly fine and compiles with GCC.

Here, you'll find deep information about what is required for a minimal allocator and what can be re-implemented for a full allocator. It seems that VS2012's std::allocator_traits has a bug, and it supposed to be fixed in VS2013 as explained here:

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top