2

I recently found the boost ptr_vector useful to manage my collection of heap-allocated objects. The pointer collection library is very nice, but unfortunately, I'm being held up by one thing.

Another part of my code needs to explicitly hold a pointer to one of my objects in the ptr_vector (for specific reasons it cannot be a reference). However, when you access an object in a ptr_vector, you get a reference, T& (even though you used ptr_vector.push_back(T *)

Is there anyway I can get a plain pointer out of a boost::ptr_vector?

cemulate
  • 2,305
  • 1
  • 34
  • 48

2 Answers2

9

Yes,

boost::ptr_vector<int> v;
v.push_back(new int());
int* ptr = &v[0];
ronag
  • 49,529
  • 25
  • 126
  • 221
3

Same way you do from a regular vector: &myvec[index]. Of course you're on your own ensuring that the pointer is not used after the object is no longer there. If this becomes difficult then you can consider switching to a vector<shared_ptr<T> > rather than a ptr_vector<T>.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699