你如何转移的boost :: ptr_vector的一个要素的所有权? [英] How do you transfer ownership of an element of boost::ptr_vector?
本文介绍了你如何转移的boost :: ptr_vector的一个要素的所有权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
的#include<升压/ ptr_container / ptr_vector.hpp>
#包括LT&;&iostream的GT;使用命名空间std;
使用名字空间boost;结构A {
〜A(){COUT<< 删除<< (无效*)该<< ENDL; }
};诠释主(){
ptr_vector< A>伏;
v.push_back(新一);
A * TEMP =&放大器; v.front();
v.release(v.begin());
删除临时;
返回0;
}
输出:
删除0x300300
删除0x300300
C(6832)的malloc:***错误对象0x300300:双重释放
块引用>解决方案
ptr_vector< A> ::发布
返回ptr_vector< A&GT ;: :auto_type
,这是一种在轻型智能指针当auto_type
项目超出范围,这件事它指向的是自动删除。要恢复原始的指针的东西,并保持它由的auto_ptr
就是拿着它,你需要调用发布$ C被删除$ C>上过:
INT的main(){
ptr_vector< A>伏;
v.push_back(新一);
A * TEMP = v.release(v.begin())发布()。
删除临时;
返回0;
}第一个
发布
通知ptr_vector
来放弃;第二讲述了的auto_ptr
来放弃了。#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
解决方案
ptr_vector<A>::release
returns aptr_vector<A>::auto_type
, which is a kind of light-weight smart pointer in that when anauto_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 theauto_ptr
that's holding it, you need to callrelease
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 theptr_vector
to give it up; the second tells theauto_ptr
to give it up too.这篇关于你如何转移的boost :: ptr_vector的一个要素的所有权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文