This is a rather academic question, I realise it matters little regarding optimization, but it is just out of interest.
From what I understand, when you call new[size]
, additional space is allocated to store the size of the allocated array. This is so when delete []
is called, it is known how much space can be freed.
What I've done is written how I think a vector would roughly be implemented:
#include <cstddef>
template <class T>
class Vector
{
public:
struct VectorStorage
{
std::size_t size;
T data[];
};
Vector(std::size_t size) : storage(new VectorStorage[size])
{
storage->size = size;
}
std::size_t size()
{
return storage->size;
}
~Vector()
{
delete[] storage;
}
private:
VectorStorage* storage;
};
As far as I can tell, size
is stored twice. Once in the VectorStorage
object directly (as it needs to be so the size()
function can work) but again in a hidden way by the compiler, so delete[]
can work.
It seems like size
is stored twice. Is this the case and unavoidable, or is there a way to ensure that the size is only stored once?