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

一世执手 提交于 2020-01-22 19:38:22

问题


#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

回答1:


ptr_vector<A>::release returns a ptr_vector<A>::auto_type, which is a kind of light-weight smart pointer in that when an auto_type item goes out of scope, the thing it points to is automatically deleted. To recover a raw pointer to the thing, and keep it from being deleted by the auto_ptr that's holding it, you need to call release on that too:

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 the ptr_vector to give it up; the second tells the auto_ptr to give it up too.



来源:https://stackoverflow.com/questions/871267/how-do-you-transfer-ownership-of-an-element-of-boostptr-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!