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
?
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.
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.
Arrays have to be deallocated explicitly if defined dynamically whereas vectors are automatically de-allocated from heap memory.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With