关于scoped_ptr智能指针
来源:互联网 发布:淘宝网羊毛衫 编辑:程序博客网 时间:2024/05/17 23:56
今天把chromium的开发环境搭建起来了,简单的看了一下里面的代码,发现里面大量的用了scoped_ptr智能指针,哎,都快忘记这个玩意了,又找资料复习一下,废话不说了
scoped_ptr 和 auto_ptr非常类似,是一个简单的智能指针,它能够保证在离开作用域后对象被自动释放。下列代码演示了该指针的基本应用:
#include<string>
#include <iostream>
#include <boost/scoped_ptr.hpp>
class implementation
{
public:
~implementation() { std::cout <<"destroying implementation\n"; }
void do_something() { std::cout << "did something\n"; }
};
void test()
{
boost::scoped_ptr<implementation> impl(new implementation());
impl->do_something();
}
void main()
{
std::cout<<"Test Begin ... \n";
test();
std::cout<<"Test End.\n";
}
该代码的输出结果是:
Test Begin ...
did something
destroying implementation
Test End.
可以看到:当implementation类离其开impl作用域的时候,会被自动删除,这样就会避免由于忘记手动调用delete而造成内存泄漏了。
scoped_ptr特点:
scoped_ptr的实现和auto_ptr非常类似,都是利用了一个栈上的对象去管理一个堆上的对象,从而使得堆上的对象随着栈上的对象销毁时自动删除。不同的是,scoped_ptr有着更严格的使用限制——不能拷贝。这就意味着:scoped_ptr指针是不能转换其所有权的。
- 不能转换所有权
scoped_ptr所管理的对象生命周期仅仅局限于一个区间(该指针所在的"{}"之间),无法传到区间之外,这就意味着scoped_ptr对象是不能作为函数的返回值的(auto_ptr可以)。 - 不能共享所有权
这点和auto_ptr类似。这个特点一方面使得该指针简单易用。另一方面也造成了功能的薄弱——不能用于stl的容器中。 - 不能用于管理数组对象
由于scoped_ptr是通过delete来删除所管理对象的,而数组对象必须通过deletep[]来删除,因此scoped_ptr是不能管理数组对象的,如果要管理数组对象需要使用scoped_array类。
- 关于scoped_ptr智能指针
- 智能指针 scoped_ptr
- 智能指针scoped_ptr
- 智能指针 scoped_ptr
- scoped_ptr智能指针(二)
- 智能指针boost::scoped_ptr
- Boost智能指针:scoped_ptr
- 智能指针(二):scoped_ptr
- 智能指针之 scoped_ptr
- 智能指针之scoped_ptr
- boost::scoped_ptr智能指针
- 智能指针之scoped_ptr
- Boost智能指针—scoped_ptr
- C++ boost智能指针scoped_ptr
- boost智能指针系列:scoped_ptr
- boost.smart_ptr-智能指针scoped_ptr
- boost.smart_ptr-智能指针scoped_ptr
- boost.smart_ptr-智能指针scoped_ptr
- i++为什么不能作为左值?
- IAR中配置头文件包含路径
- mybatis分页 sql 语句
- 蓝港在线CEO王峰:我在网络游戏行业十年从业记
- ArcGIS server9.3实现根据坐标定位
- 关于scoped_ptr智能指针
- Delphi Open Tools API概述
- tsung--开源多协议分布式压力测试工具
- 冒泡算法简单例子_Java
- GUI
- sqlservice 取得 6 到10 行数据
- STL提供了三个最基本的容器:vector,list,deque
- WIN32程序IP Control实现禁止输入非法字符
- PDF文件简介及PDF文档加密方法