Make vector resize / reserve simple

This commit is contained in:
2019-05-18 13:04:39 +02:00
parent 2ce294c40b
commit 475b7c531b

View File

@@ -7,7 +7,6 @@ class Vector
{ {
private: private:
T * data; T * data;
std::size_t byteSize;
std::size_t reserveSize; std::size_t reserveSize;
std::size_t size; std::size_t size;
@@ -17,27 +16,21 @@ private:
{ {
std::free(data); std::free(data);
data = nullptr; data = nullptr;
byteSize = 0ul;
reserveSize = 0ul; reserveSize = 0ul;
return; return;
} }
std::size_t newByteSize = allocationSize * sizeof(T); if(allocationSize == size)
newByteSize += newByteSize % 32ul; // Allocate in blocks of 32 bytes
if(newByteSize <= byteSize)
{ {
reserveSize = allocationSize;
return; return;
} }
void * result = std::realloc(data, newByteSize); void * result = std::realloc(data, sizeof(T) * allocationSize);
if(result == nullptr) if(result == nullptr)
{ {
throw std::runtime_error("Cannot allocate the requested size of memory."); throw std::runtime_error("Cannot allocate the requested size of memory.");
} }
byteSize = newByteSize;
reserveSize = allocationSize; reserveSize = allocationSize;
data = reinterpret_cast<T *>(result); data = reinterpret_cast<T *>(result);
} }
@@ -82,7 +75,6 @@ public:
Vector() Vector()
: data(nullptr), : data(nullptr),
byteSize(0ul),
reserveSize(0ul), reserveSize(0ul),
size(0ul) size(0ul)
{} {}