#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;
}
输出:
deleted 0x300300 deleted 0x300300 c(6832) malloc: *** error for object 0x300300: double free
答案 0 :(得分:15)
ptr_vector<A>::release
返回ptr_vector<A>::auto_type
,这是一种轻量级智能指针,当auto_type
项超出范围时,它指向的内容会自动删除。要恢复指向该事物的原始指针,并使其不被被持有它的auto_ptr
删除,您还需要在其上调用release
:
int main() {
ptr_vector<A> v;
v.push_back(new A);
A *temp=v.release(v.begin()).release();
delete temp;
return 0;
}
第一个release
告诉ptr_vector
放弃它;第二个告诉auto_ptr
也放弃它。