使用Boost库中的组件进行C++内存管理
C++标准库中的auto_ptr,智能指针,部分的解决了获取资源自动释放的问题
在Boost中,提供了6中智能指针:scoped_ptr, scoped_array, shared_ptr, shared_array, weak_ptr, instrusive_ptt,这些智能指针属于smart_ptr组件
使用时: #include <boost/smart_ptr.hpp> using namespace std;
接下来介绍前四个智能指针
scoped_ptr
template<class T> class scoped_ptr // noncopyable
{
private: T * px; scoped_ptr(scoped_ptr const &);
scoped_ptr & operator=(scoped_ptr const &); typedef scoped_ptr<T> this_type; void operator==( scoped_ptr const& ) const;
void operator!=( scoped_ptr const& ) const; public: typedef T element_type; explicit scoped_ptr( T * p = 0 ): px( p ) // never throws
{
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
boost::sp_scalar_constructor_hook( px );
#endif
} #ifndef BOOST_NO_AUTO_PTR explicit scoped_ptr( std::auto_ptr<T> p ): px( p.release() ) // never throws
{
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
boost::sp_scalar_constructor_hook( px );
#endif
} #endif ~scoped_ptr() // never throws
{
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
boost::sp_scalar_destructor_hook( px );
#endif
boost::checked_delete( px );
}
。。。。。
摘抄与boost/smart_ptr/scoped_ptr.hpp中
scoped_ptr:是一个很类似auto_ptr的智能指针,它包装了new操作符在堆上分配的动态对象,能够保证动态创建的对象在任何时候都可以被正确的删除,但是scoped_ptr的所有权不能被转移,一旦scoped_ptr会获得了对象的管理权,你就无法再从它那里取回来。因为scoped_ptr同时将拷贝构造函数和赋值操作符都声明为私有的(只在本作用域里使用,不希望被转移)
#include <boost/smart_ptr.hpp>
#include <iostream>
#include <cassert>
using namespace boost;
using namespace std; struct posix_file { //一个示范的文件类
posix_file(const char *file_name)
{ cout << "open file: " << file_name << endl; }
~posix_file() { cout << "close file" << endl; }
}; int main(void)
{
scoped_ptr<int> p(new int); //一个int指针的scoped_ptr
if(p)
{
*p=100;
cout << *p << endl;
}
p.reset(); //reset()置空scoped_ptr
assert(p==0);
if(!p)
{
cout << "scoped_ptr==null" << endl;
}
scoped_ptr<posix_file> fp(new posix_file("/tmp/a.txt")); auto_ptr<int> ap(new int(10)); //一个int的自动指针
scoped_ptr<int> sp(ap);
assert(ap.get() == 0); //原auto_ptr不再拥有指针 ap.reset(new int(20));
cout << *ap << "," << *sp << endl; auto_ptr<int> ap2;
ap2=ap; //ap2从ap获得原始指针,发生所有权转移
assert(ap.get()==0);
//scoped_ptr<int> sp2;
//sp2=sp; //赋值操作错误
return 0;
}
(摘抄于深入C++“准标准库”)
scoped_array
template<class T> class scoped_array // noncopyable
{
private: T * px; scoped_array(scoped_array const &);
scoped_array & operator=(scoped_array const &); typedef scoped_array<T> this_type; void operator==( scoped_array const& ) const;
void operator!=( scoped_array const& ) const; public: typedef T element_type; explicit scoped_array( T * p = 0 ) : px( p ) // never throws
{
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
boost::sp_array_constructor_hook( px );
#endif
} ~scoped_array() // never throws
{
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
boost::sp_array_destructor_hook( px );
#endif
boost::checked_array_delete( px );
}
。。。。
#include <boost/smart_ptr.hpp>
using namespace boost;
using namespace std; int main(void)
{
int *arr = new int[100];
scoped_array<int> sa(arr); //fill_n(&sa[0], 100, 5); //用标准库函数赋值
fill(&sa[0], &sa[99], 5);
sa[10] = sa[20]+sa[30]; //只能用operator[]来访问数组元素
cout << sa[10] << endl;
//cout << *(sa+20) << endl; //没有* ->运算符
return 0;
}
shared_ptr
template<class T> class shared_ptr
{
private: // Borland 5.5.1 specific workaround
typedef shared_ptr<T> this_type; public: typedef T element_type;
typedef T value_type;
typedef T * pointer;
typedef typename boost::detail::shared_ptr_traits<T>::reference reference; shared_ptr(): px(0), pn() // never throws in 1.30+
{
} template<class Y>
explicit shared_ptr( Y * p ): px( p ), pn( p ) // Y must be complete
{
boost::detail::sp_enable_shared_from_this( this, p, p );
} //
// Requirements: D's copy constructor must not throw
//
// shared_ptr will release p by calling d(p)
// template<class Y, class D> shared_ptr(Y * p, D d): px(p), pn(p, d)
{
boost::detail::sp_enable_shared_from_this( this, p, p );
} // As above, but with allocator. A's copy constructor shall not throw. template<class Y, class D, class A> shared_ptr( Y * p, D d, A a ): px( p ), pn( p, d, a )
{
boost::detail::sp_enable_shared_from_this( this, p, p );
}
class shared
{
public:
shared(shared_ptr<int> p_) : p(p_) {} //构造函数初始化成员变量
void print()
{
cout << "count: " << p.use_count() << "v = " << *p << endl;
}
private:
shared_ptr<int> p;
}; void print_func(shared_ptr<int> p)
{
cout << "count: " << p.use_count() << "v = " << *p << endl;
} int main(void)
{
shared_ptr<int> p(new int(10));
shared s1(p), s2(p); s1.print();
s2.print(); *p=20;
print_func(p);
s1.print();
return 0;
}
用于标准容器
int main(void)
{
typedef vector<shared_ptr<int> > vs;
vs v(10); int i=10;
for (vs::iterator pos=v.begin(); pos!=v.end(); pos++)
{
*pos = make_shared<int>(++i);
cout << *(*pos) << " ";
}
cout << endl; shared_ptr<int> p = v[9];
*p = 100;
cout << *v[9] << endl;
return 0;
}
使用Boost库中的组件进行C++内存管理的更多相关文章
- boost库中的 program_options
1.阅读rviz中的源码时在rviz/visualizer_app.cpp中遇到如下代码: po::options_description options; options.add_options() ...
- boost库中sleep方法详解
博客转载自:https://blog.csdn.net/huang_xw/article/details/8453506 boost库中sleep有两个方法: 1. 这个方法只能在线程中用, 在主线程 ...
- 详解boost库中的Message Queue .
Message Queue(后文简写成MQ或消息队列)是boost库中用来封装进程间通信的一种实现,同一台机器上的进程或线程可以通过消息队列来进行通迅.消息队列中的消息由优先级.消息长度.消息数据三部 ...
- 【Boost】boost库中timer定时器 1
博客转载自:http://blog.csdn.net/liujiayu2/article/details/50384537 同步Timer asio中提供的timer名为deadline_timer, ...
- C++中的垃圾回收和内存管理
最开始的时候看到了许式伟的内存管理变革系列,看到性能测试结果的时候,觉得这个实现很不错,没有深入研究其实现.现在想把这个用到自己的一个项目中来,在linux下编译存在一些问题,所以打算深入研究一下. ...
- Swift中的可选链与内存管理(干货系列)
干货之前:补充一下可选链(optional chain) class A { var p: B? } class B { var p: C? } class C { func cm() -> S ...
- 高端内存映射之vmalloc分配内存中不连续的页--Linux内存管理(十九)
1 内存中不连续的页的分配 根据上文的讲述, 我们知道物理上连续的映射对内核是最好的, 但并不总能成功地使用. 在分配一大块内存时, 可能竭尽全力也无法找到连续的内存块. 在用户空间中这不是问题,因为 ...
- Java中的垃圾回收机制&内存管理&内存泄漏
1. Java在创建对象时,会自动分配内存,并当该对象引用不存在的时候,释放这块内存. 为什么呢? 因为Java中使用被称为垃圾收集器的技术来监视Java程序的运行,当对象不再使用时,就自动释放对象所 ...
- 【Boost】boost库中timer定时器 2
博客转载自:http://blog.csdn.net/yockie/article/details/40386145 先跟着boost文档中asio章节的指南中的几个例子学习一下使用: 所有的Asio ...
随机推荐
- c语言,数组和字符串
1. “数组名代表了数组的存储首地址,是一个地址常量”. 对于char *p1 = "A String."; 和 char p2[] = "Another String. ...
- 多文件上传组件FineUploader使用心得
原文 多文件上传组件FineUploader使用心得 做Web开发的童鞋都知道,需要经常从客户端上传文件到服务端,当然,你可以使用<input type="file"/> ...
- GAE+bottle+jinja2+beaker快速开发demo - Python,GAE - language - ITeye论坛
GAE+bottle+jinja2+beaker快速开发demo - Python,GAE - language - ITeye论坛 :GAE+bottle+jinja2+beaker快速开发 ...
- asp.net2.0安全性(1)--用户角色篇(代码实现2)--转载来自车老师
加载所有用户 MembershipUserCollection user = Membership.GetAllUsers(); listUser.DataSource = user; listUse ...
- 在Python中使用正则表达式同时匹配邮箱和电话并进行简单的分类
在Python使用正则表达式需要使用re(regular exprssion)模块,使用正则表达式的难点就在于如何写好p=re.compile(r' 正则表达式')的内容. 下面是在Python中使用 ...
- 基于visual Studio2013解决面试题之0510连续数之和
题目
- Not able to reset SmartRF04DD
今天在使用使用CC2540的时候,想下载个程序到CC2540底板上,结果出现Not able to reset SmartRF04DD的错误.如下图 经过一番摸索,最终是按下CCDEBUG上的rese ...
- 性能测试之LoardRunner 自动关联
1.什么是自动关联? 2.实例介绍 以下是详细介绍: 自动化关联:它是VuGen提供的自动化扫描关联处理策略,它的原理是对同一个脚本运行和录制时的服务器返回进行比较,来自动查找变化的部分,并且提示是否 ...
- jquery mobile实现拨打电话功能的几种方法
3.使用wtai协议进行拨打电话. 在wml中可以调用设备的wtai函数来呼叫特定的电话号码.目前,越来越多的浏览器都支持这个功能,但还不是所有. 代码如下所示: 复制代码 代码如下: <inp ...
- 【Cocos2d-X游戏实战开发】捕鱼达人之开发前准备工作(一)
本系列学习教程使用的是cocos2d-x-2.1.4(最新版为cocos2d-x-2.1.5) 博主发现前两个系列的学习教程被严重抄袭,在这里呼吁大家请尊重开发者的劳动成果, 转载的时候请务必注明出处 ...