How do you transfer ownership of the boost :: ptr_vector element?

#include <boost/ptr_container/ptr_vector.hpp> #include <iostream> using namespace std; using namespace boost; struct A { ~A() { cout << "deleted " << (void*)this << endl; } }; int main() { ptr_vector<A> v; v.push_back(new A); A *temp = &v.front(); v.release(v.begin()); delete temp; return 0; } 

outputs:

 deleted 0x300300 deleted 0x300300 c(6832) malloc: *** error for object 0x300300: double free 
+7
c ++ boost
source share
1 answer

ptr_vector<A>::release returns a ptr_vector<A>::auto_type , which is a kind of light smart pointer, when the auto_type element goes out of scope, what it indicates is automatically deleted. To restore the raw pointer to an item and not delete it with auto_ptr , which holds it, you also need to call release :

 int main() { ptr_vector<A> v; v.push_back(new A); A *temp=v.release(v.begin()).release(); delete temp; return 0; } 

The first release tells ptr_vector to abandon it; the second tells auto_ptr also abandon it.

+15
source share

All Articles