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?
Asked
Active
Viewed 256 times
0
-
Exact same thing. Just remember not to change the vector's size, because the memory is reallocated and it will cause all the pointers to those objects to invalidate. – Yochai Timmer Oct 04 '13 at 22:23
-
1Store objects instead of pointers in your vector and they are guaranteed to be contiguous. – goji Oct 04 '13 at 22:24
-
1If you use `vector
` instead of `vector – Praetorian Oct 04 '13 at 22:24` the objects will be laid out contiguously in memory. -
yse a custom allocator that uses a contiguos memory? – Karoly Horvath Oct 04 '13 at 22:33
-
Related question: http://stackoverflow.com/questions/247738/is-it-safe-to-assume-that-stl-vector-storage-is-always-contiguous – Ferruccio Oct 04 '13 at 23:07
2 Answers
1
"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.

LihO
- 41,190
- 11
- 99
- 167
-
@Troy: Yet I believe that this is not the case. But I rephrased my answer :) – LihO Oct 04 '13 at 22:28
0
Use custom allocator while creating the vector. Your allocator can pre-allocate memory the way you need it.

Iuri Covalisin
- 645
- 4
- 7