Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correctly allocate memory in vector

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?

like image 655
Hrant Avatar asked Sep 23 '15 14:09

Hrant


People also ask

How do you allocate space to a vector?

You can use the reserve() and resize() methods to have it allocate enough memory to fit a given amount of items: std::vector<int> vec1; vec1. reserve(30); // Allocate space for 30 items, but vec1 is still empty.

How is a vector stored in memory?

Vectors are assigned memory in blocks of contiguous locations. When the memory allocated for the vector falls short of storing new elements, a new memory block is allocated to vector and all elements are copied from the old location to the new location. This reallocation of elements helps vectors to grow when required.

Do vectors dynamically allocate memory?

Arrays have to be deallocated explicitly if defined dynamically whereas vectors are automatically de-allocated from heap memory.

Does vector always allocate on heap?

vector has an internal allocator which is in charge of allocating/deallocating memories from heap for the vector element . So no matter how you create a vector, its element is always allocated on the heap .


1 Answers

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.

like image 88
Sebastian Redl Avatar answered Oct 27 '22 01:10

Sebastian Redl