0

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?

Community
  • 1
  • 1
Rob Boc
  • 3
  • 1

2 Answers2

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
0

Use custom allocator while creating the vector. Your allocator can pre-allocate memory the way you need it.

Iuri Covalisin
  • 645
  • 4
  • 7