Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

c++ - How to use std::allocator<T> appropriately in Vector implementation

I'm trying to replicate the vector implementation on my own but I'm struggling with the allocator. Basically I am trying to use the .allocate() member function of std::allocator to allocate some memory without constructing anything but I'm failing.

This is the code that causes me trouble, and I think I'm doing it wrongly. Would appreciate any help with this. I noticed that removing const & from the parameter works, but I still think this is not the correct way.

namespace container {

    template<typename Type, typename Allocator = std::allocator<Type>>
    class vector
    {
    private:
        Type* m_vector;
        std::size_t m_capacity{};
        std::size_t m_size{};


    public:
        // Aliases  
        using size_type = std::size_t;
        using init_list_type = std::initializer_list<Type>;
        using reference = Type&;
        using const_reference = const Type&;
        using pointer = Type*;
        using const_pointer = const Type*;

        // Constructors
        constexpr vector() noexcept : m_vector{ nullptr } {}
        constexpr explicit vector(size_type length, const Allocator& allocator = Allocator()) // Here is the issue, this doesn't work if allocator is const&, but it works if it's not 
            : m_vector{ allocator.allocate(length) }, m_size{ length }, m_capacity{ length } {}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should keep a copy of the allocator in the vector object. You'll need it in the destructor to deallocate the memory that you allocated in the constructor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...