Search code examples
c++memoryvectorentity-component-system

Is it a good practice to use a vector of bytes as raw storage for other types?


I've started to follow an ECS tutorial on YouTube and I've never seen anyone allocating a new variable into a vector of uint8 before.

template<typename Component>
uint32 ECSComponentCreate(Array<uint8>& memory, EntityHandle entity, BaseECSComponent* comp)
{
    uint32 index = memory.size();
    memory.resize(index+Component::SIZE);
    Component* component = new(&memory[index])Component(*(Component*)comp);
    component->entity = entity;
    return index;
}

(the full code in question can be found here; Array here is #define Array std::vector)

How does it differ from using a vector of pointers, why is it better?


Solution

  • That's basically a "pool allocator." Now that you know what it's called you can read about why it's done, but performance is generally the motivation.

    All the allocations are done in a single vector, and at the end the whole vector can be deallocated at once (after destroying the objects within, which you can see in the deallocation function just below).