EDIT: A better title for this would be: polymorphism for large collections of objects without individual heap allocations.
Suppose that I have a base class Animal
with virtual functions and some derived classes (Cat
, Dog
, etc.). The real derived classes contain 4-8 bytes of data. I want to store a std::list<Animal>
which actually contains items which are derived objects. I want to avoid the creation of many small objects on the heap using new.
Is there any design pattern which can be used to achieve this?
EDIT: My ideas to implement this
- create
std::deque<Cat>
,std::deque<Dog>
, ...; storestd::list<Animal*>
which contains pointers from thedeques
; I use thestd::deque
because I suppose that it has a good memory management with chunks of objects;
char
on the heap and use placement new if you wanted. But remember that the creation of many small objects on the heap using new is better than the creation of many large objects on the heap using new. And the only way to use polymorphism without pointers is with references. – Melee