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?

5
  • 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. Commented Oct 4, 2013 at 22:23
  • 1
    Store objects instead of pointers in your vector and they are guaranteed to be contiguous. Commented Oct 4, 2013 at 22:24
  • 1
    If you use vector<T> instead of vector<T*> the objects will be laid out contiguously in memory. Commented Oct 4, 2013 at 22:24
  • yse a custom allocator that uses a contiguos memory? Commented Oct 4, 2013 at 22:33
  • Related question: stackoverflow.com/questions/247738/… Commented Oct 4, 2013 at 23:07

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Troy: Yet I believe that this is not the case. But I rephrased my answer :)
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.