Correctly allocate memory in vector
Asked Answered
D

1

8

I am trying to implement std::vector as a programming exercise.

Consider the following code snippet:

template <class T, class Allocator = std::allocator<T>>
class vector
{
public:
    using size_type = size_t;
    using allocator_type = Allocator;
    ...
private:
    T* m_data;
    allocator_type m_alloc;
    size_type m_capacity;
    ...
}; 

m_data has type T*. I need to allocate memory using std::allocator_traits<allocator_type>::allocate(m_alloc, m_capacity) which returns std::allocator_traits<allocator_type>::pointer.

Can I assume that pointer can be implicitly cast to T* and assign the value returned from allocate to m_data?

If not, how to correctly allocate memory in vector?

Dissentious answered 23/9, 2015 at 14:43 Comment(2)
You could make your own allocator.Broccoli
Related: https://mcmap.net/q/1210953/-custom-pointer-types-and-container-allocator-typedefsHandle
M
7

You should make your m_data member an Allocator::pointer. (You should probably make a local alias of that type in your vector, if you want to follow the standard interface.)

The type is there because some allocators don't deal in raw pointers, like the Boost.Interprocess shared memory allocator, which may use smart pointers depending on configuration.

Matronly answered 23/9, 2015 at 14:58 Comment(2)
If I define m_data as Allocator::pointer, what should std::vector::data() function return? Its return type is T*.Dissentious
@Dissentious You should return std::addressof(*m_data)Matronly

© 2022 - 2024 — McMap. All rights reserved.