你如何转移boost :: ptr_vector元素的所有权?

时间:2009-05-15 23:34:28

标签: c++ boost

#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

1 个答案:

答案 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也放弃它。