0

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 } {}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This will solve your const problem, too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.