Uncle Crusty
Uncle Crusty

Reputation: 75

Pointer to vector for sake of polymorphism - C++

I am working on an OpenGL based game, and this problem arises in my search for a robust way to pass entity information to the rendering and networking functions.

Something like this:

vector <DynamicEntity> DynamicEntities;
vector <StaticEntity> StaticEntities;

vector <Entity> *Entities;

Entities.push_back(&DynamicEntities);
Entities.push_back(&StaticEnt);

Graphics.draw(Entities);
Server.bufferData(Entities);

The only information Graphics.draw and Server.bufferData need is contained by Entity, which both DynamicEntity and StaticEntity inherit from.

I know this would work:

vector <Entity*> Entities;
for(uint32_t iEntity=0;iEntity<iNumEntities;iEntity++)
{
    Entities.push_back(&DynamicEntities[iEntity])
}
//(ad nauseam for other entity types)

but that seems awfully inefficient, and would have to account for changing numbers of entities as the game progresses. I know relatively little of the underpinnings of data structures; so this may be a stupid question, but I would appreciate some insight.

Upvotes: 3

Views: 80

Answers (1)

Joe Z
Joe Z

Reputation: 17936

That copy operation in the for loop you show is likely to be so fast as to be unmeasurable as compared to the cost of drawing the graphics. You may be able to make it faster still by doing Entities.resize(...) before the loop and using array indexing in the loop.

The solution you propose in the first part of your question will not work, because the data layout for a vector<StaticEntity> likely differs from the layout for a vector<DynamicEntity>. Arrays of objects are not polymorphic, and the storage managed by vector<> is essentially an array with some dynamic management around it.

In fact, because the vector storage is array-like, if you replace push_back with array indexing, the body of for loop will compile to something resembling:

*p1++ = p2++;

which the compiler may even auto-vectorize!

Upvotes: 3

Related Questions