Reputation: 47
I am currently working on a small game in C++17. To manage elements in the game, I use an ordinary std::vector, which is supposed to manage elements of my cEntity class type.
In the code I currently have it defined like this
std::vector<cEntity> gameEntities;
In the code I also have a function add(), which should add elements of type cEntity.
For example:
void addEntity(void)
{
gameEntities.emplace_back( cEntity{"default values"});
}
Is that performant? I wonder if a cEntity is first created here using the stack and then copied into the vector? Would it be better / more efficient if I didn't manage the specific objects at all, but Smart Pointers instead?
For example:
std::vector<std::unique_ptr<cEntity>> gameEntities;
void addEntity(void)
{
gameEntities.emplace_back(std::make_unique<cEntity>("default values"));
}
Is it faster? The object of type cEntity is created on the heap and only the unique pointer is stored in the vector using move() semantics? I'm not sure about that... With C++ it's always said that you should use the stack wherever possible...
Thank you for a little explanation.
Upvotes: 0
Views: 176
Reputation: 123450
For performant insertion of many elements into a vector you should either reserve or resize (whichever is more appropriate) upfront to make enough space once and avoid frequent reallocations. Reallocation strategies of std::vector
are good (resulting in amortized constant complexity), but sometimes you can do better.
Moreoever, emplace_back
is to pass parameters that will be forwarded to the elements constructor so that the element can be constructed in place. When you call emplace_back
with an element it is no more efficient than push_back
. The real power of emplace_back
is only used when you do not create the element outside the vector and then move it into the vector, but rather only let it be constructed in place.
Upvotes: 2