0

I'd like to create an object bool using a vector of type X objects. When I create the vector:

vector<X>* v = new vector<X>;
v.reserve(10000);

I want the minimal work done as possible. Will just the default constructor get called (my default constructor is empty for X)?

Later on in my program how do I "create" my object using the object pool? Would it be something like:

int y = get_next_object_in_pool();
X x = v[y];

where get_next_object_in_pool() just keeps an index to the next free index in the vector?

user997112
  • 29,025
  • 43
  • 182
  • 361
  • Note that you should write `vector* v = new vector;` or `vector v();` – Masood Khaari Oct 05 '13 at 13:51
  • This code saved me once years ago: [Object Pooling for Generic C++ classes](http://www.codeproject.com/Articles/3968/Object-Pooling-for-Generic-C-classes) It has minimal intrusion to your existing code, as you use normal `new` and `delete` operators to get objects from the pool and return them back to. – Masood Khaari Oct 05 '13 at 13:55
  • @MassoodKhaari thanks for pointing out my missing pointer reference. – user997112 Oct 05 '13 at 17:40
  • Now you should use "->" instead of "." :) – Masood Khaari Oct 06 '13 at 05:09

1 Answers1

0

No constructor for X will get called because reserve doesn't create any objects. Don't confuse reserve with resize, they do different things. I think from the rest of your description you do want reserve, but remember it leaves your vector at size 0.

When you want to add an object to the pool it's something like

v.push_back(X());

assuming you want to add a default constructed object.

If you want complete control over your pool, with any old mix of constructed and non-constructed slots in your pool. then you're going to have to do something else. You won't get that with vector<T>.

john
  • 85,011
  • 4
  • 57
  • 81
  • Cool so I just create my X object using my non-default constructor and then push_back on to the vector as and when. And this will keep my X objects in continuous memory? – user997112 Oct 05 '13 at 12:27
  • @user997112 yes, vector is guaranteed to use contiguous memory. – john Oct 05 '13 at 12:29