Search code examples
c++pointersboostvectorptr-vector

Randomly assign to boost::ptr_vector


I want to randomly assign to a boost::ptr_vector. Using the normal STL vector I would do this:

class A{

};

A* a1 = new A();
A* a2 = new A();

vector<A*> normal_vec;
normal_vec.resize(2);
normal_vec[1] = a1;
normal_vec[0] = a2;

I am trying to do the same with boost::ptr_vector:

A* a1 = new A();
A* a2 = new A();

ptr_vector<A> boost_vec;
boost_vec.resize(2);

boost_vec[1] = a1;
boost_vec[0] = a2;

But am getting the following error:

no match for ‘operator=’ in ‘v.boost::ptr_vector<A>::<anonymous>.boost::ptr_sequence_adapter<T, VoidPtrSeq, CloneAllocator>::operator[] [with T = A, VoidPtrSeq = std::vector<void*, std::allocator<void*> >, CloneAllocator = boost::heap_clone_allocator, boost::ptr_sequence_adapter<T, VoidPtrSeq, CloneAllocator>::reference = A&, boost::ptr_sequence_adapter<T, VoidPtrSeq, CloneAllocator>::size_type = long unsigned int](1ul) = a1’

But am struggling to make sense of this


Solution

  • You should use ptr_vector<T>::replace instead of operator[]. The operator[] returns T& instead of T*&, so you can only assign value not a pointer.

    Also note that you have a memory leak when the second new for a2 throws, a1 is not deleted in the code below:

    A* a1 = new A();
    A* a2 = new A();
    

    Consider using std::unique_ptr.