I need to create objects dynamically and would like to use vectors to do that. I understand that the pointers to the objects would be stored in the vector and they would be contiguous but the actual object will not be. I can do it as given in Create objects in pre-allocated memory . However, I would prefer to use vectors. Is there any way I could do so?
2 Answers
"I need to create objects dynamically"
Are you REALLY sure you NEED the dynamic allocation? If it is possible, use vector of objects instead:
std::vector<T> myObjects(100); this allocates the single block of memory big enough to hold 100 instances of T and initializes them using the default constructor.
1 Comment
LihO
@Troy: Yet I believe that this is not the case. But I rephrased my answer :)
vector<T>instead ofvector<T*>the objects will be laid out contiguously in memory.