偶尔在一本书上看到了称为智能指针的auto_ptr能自动释放没有释放的对象,刚开始很好奇,不知道是用什么原理,后面查了一下资料才发现,这个原理很简单,其实就是用到了在栈上创建的对象随之栈的释放自动调用析构函数的原理,在加上对c++函数模板的巧妙运用。以下例子希望能给读者带来帮助, 若有不对的地方欢迎指出。
动态分配资源的自动释放的英文是Resource Allocation In Initialization,通常缩写成RAII。
根据《C++ Primer》第4版:
During stack unwinding, the function containing thethrow,
and possibly other functions in the call chain, are exited prematurely. In general, these functions will have created local objects that ordinarily would be destroyed when the function exited. When a function is exited due to an exception, the compiler guarantees
that the local objects are properly destroyed. As each function exits, its local storage is freed. … If the local object is of class type, the destructor for this object is called automatically. As usual, the compiler does not work to destroy an object of
built-in type.
假定有一个类定如下:
// 资源类
class Student
{
public:
Student(const string name = "Andrew", string gender = "M", int age = 6)
{
this->name = name;
this->gender = gender;
this->age = age;
}
void printStudentInfo()
{
cout << "Name: " << name << " ";
cout << "Gender: " << gender << " ";
cout << "Age: " << age << endl;
//throw runtime_error("Throw an exception deliberately..."); // (1)
}
~Student()
{
// 下面这条语句用来提示资源是否被释放了
cout << "The destructor of class Student is called" << endl;
}
private:
string name;
string gender;
int age;
};
那么类似下面代码中的方式使用Student这个类,就会造成内存泄漏:
//测试代码
intmain()
{
Student *stu =newStudent("Andrew","M", 6);
stu->printStudentInfo();
return0;
}
因为在return之前,没有delete掉stu这个动态分配而来的资源(如果仅仅是这个程序,也没有内存泄漏之忧,因为整个应用都结束运行了,在此只是为了方便说明类似的使用方式是不可以的,即用了new动态分配了资源,而没有对应的delete去回收)。为了防止这样的方式造成的内存泄漏,上面的测试代码应该增加一行delete
stu:
//测试代码
intmain()
{
Student *stu =newStudent("Andrew","M", 6);//
(2)
stu->printStudentInfo();
deletestu;//
(3)
return0;
}
这样就不会造成内存泄漏了。运行该应用,输出的结果是:
Name: Andrew Gender: M Age: 6
The destructor of class Student is called
输出的The destructor of class Student is called表明了Student类的析构函数得到了调用。
现在,如果在(2)和(3)中间发生了异常,即将Student类中的(1)语句uncomment掉,就会出现下面这样的错误提示:
This application has requested the Runtime to terminate it in an unusual way. Please contact the application’s support team for more information.
这样一来语句(3)即delete
stu;就不会得到执行,因此也会造成内存泄漏。为了消除上面的错误,我们在前面的测试代码中,增加try-ctach来捕获异常,代码如下:
//测试代码
intmain()
{
Student *stu =newStudent("Andrew","M", 6);//
(2)
try
{
stu->printStudentInfo();
}
catch(constexception &e)
{
cout << e.what() << endl;
}
deletestu;//
(3)
return0;
}
输出结果:
Name: Andrew Gender: M Age: 6
Throw an exception deliberately…
The destructor of class Student is called
这就说明,如果增加了try-catch,后面的delete
stu;就会将用new动态分配的资源正确的予以释放。
进一步地,如果在stu->printStudentInfo();中出现了异常,而且后面也没有delete
stu;这样的语句,用new分配给stu的资源进行自动释放?办法是有的。为此,我们需要增加一个类,定义如下:
// 资源管理类
template<typename T>
class Resource
{
public:
Resource(T* p)
{
// 将新分配的到的资源的地址赋给res,现在res指向了新分配到的资源
res = p;
}
~Resource()
{
if(res)
{
// 如果res指向的地址中,资源还没有被释放,那么则释放之
delete res;
res = 0;
cout << "Resources are deallocated here." << endl;
}
}
private:
T *res;
};
把测试代码改为:
//测试代码
intmain()
{
Student *stu =newStudent("Andrew","M", 6);//
(2)
//将stu绑定到Resource<Student>类型的res变量,res是一个local对象,当程序超出其可见范围时
//其析构函数会自动执行。而它的析构函数中,又会自动释放stu所指向的资源
Resource<Student> res(stu);
try
{
stu->printStudentInfo();
}
catch(construntime_error &e)
{
cout << e.what() << endl;
}
return0;
}
上面代码的运行结果:
Name: Andrew Gender: M Age: 6
Throw an exception deliberately…
The destructor of class Student is called
Resources are de-allocated here.
这说明即使没有delete stu;程序也正确地析构了相关动态非配的资源,从而实现了动态分配资源的自动释放。
在上面的代码中,我们用stu->printStudentInfo();来调用相关的函数,如果想用res直接调用,则需要重载Resource类的->操作符,代码如下:
// 资源管理类
template<typename T>
class Resource
{
public:
Resource(T* p)
{
// 将新分配的到的资源的地址赋给res,现在res指向了新分配到的资源
res = p;
}
~Resource()
{
if(res)
{
// 如果res指向的地址中,资源还没有被释放,那么则释放之
delete res;
res = 0;
cout << "Resources are deallocated here." << endl;
}
}
T* operator->() const
{
if(res)
return res;
else
cout << "The underlying object is empty." << endl;
}
private:
T *res;
};
粗体字部分重载了->操作符,用来返回该类中的私有成员变量res。
相应的,测试代码做如下修改:
//测试代码
intmain()
{
Student *stu =newStudent("Andrew","M", 6);//
(2)
//将stu绑定到Resource<Student>类型的res变量,res是一个local对象,当程序超出其可见范围时
//其析构函数会自动执行。而它的析构函数中,又会自动释放stu所指向的资源
Resource<Student> res(stu);
try
{
//stu->printStudentInfo();//这行被注释掉
res->printStudentInfo();//改用res来调用printStudentInfo
}
catch(construntime_error &e)
{
cout << e.what() << endl;
}
return0;
}
运行结果和前面是一致的,也实现了动态分配资源的自动释放。事实上,这就是大名鼎鼎的auto_ptr的实现原理。
注意,代码开始处需要包含以下语句:
#include<iostream>
#include<string>
#include<stdexcept>//处理异常时,必须包含此头文件
usingnamespacestd;
auto_ptr的缺陷
上面我实现的my_auto_ptr基本上是实现了auto_ptr的所有核心功能.从里面我们可以明显的看到一个很大缺陷.我们看到当通过复构造函数,通过操作符=赋值后,原来的那个智能指针对象就失效了.只有新的智能指针对象可以有效使用了.用个专业点的说法叫所有权的转移.被包装的指针指向的内存块就像是一份独享占用的财产,当通过复制构造,通过=赋值传给别的智能指针对象时,原有的对象就失去了对那块内存区域的拥有权.也就是说任何时候只能有一个智能指针对象指向那块内存区域,不能有两个对象同时指向那块内存区域.
这样一来auto_ptr不能做为STL中容器的元素,为啥呢? 因为容器中经常存在值拷贝的情况嘛,把一个容器对象直接赋值给另一对象.完了之后两个容器对象可得都能用啊.而如果是auto_ptr的话显然赋值后只能一个有用,另一个完全报废了.另外比如你有个变量auto_ptr<int> ap( new int(44) ); 然后ap被放进一个容器后,ap就报废不能用了.
不过没办法啊,在c++ 11标准之前,现在我们大部分用的是98标准吧,STL里面只有auto_ptr这一种智能指针.而在11标准中除了auto_ptr还有如下三种:
unique_ptr
smart pointer with unique object ownership semantics
只能有一个主人的指针,可以用于STL容器
shared_ptr
smart pointer with shared object ownership semantics
可共享的指针
weak_ptr
weak reference to an object managed by std::shared_ptr
弱引用指针
分享到:
相关推荐
svn自动编译安装脚本,脚本分2部分 atuo_svn.sh 是编译安装svn make_svn.sh是自动安装一个指定的库
auto cad 2014 apartment plan
ATUO-CAD教案.doc
ATUO-CAD教案.pdf
F2: 实现作图窗和文本窗口的切换 F3: 控制是否实现对象自动捕捉 F4: 数字化仪控制 F5: 等轴测平面切换 F6: 控制状态行上坐标的显示方式 F7: 栅格显示模式控制 F8: 正交模式控制 F9: 栅格捕捉模式控制 ...
atuo.js实现自动点击红包雨。通过auto自动化实现。里面的功能是通过定位找色点击。来实现的。里面有不足之处希望大家自己可以改正。也可以提出来帮助完善
Atuo cad标注直径和公差的方法。是不用鼠标点击快速标注的方法。
对于U盘带病毒的, 用这个软件最好 , 比杀毒软件好用, 长期用电脑的技术人员必备
kill_atuo专杀工具
该资源包括涉及到的GGJ/GGS电气原理接线图和高压10kv配电柜全套电气接线图,格式均为DWG格式,可直接参考使用,同时适用于学校实验室的安装图,可用于期末交作业参考的基础,共包括高低压九张图纸。
atuo typeyng keyboard system
AtuoLisp培训资料,言简意赅,精辟入里
学习AutoCAD很好的辅助,可以看着他自己慢慢的学
谷歌前几天发布了一个名为通用音乐播放器的示例应用程序,它可以在智能手机,平板产电脑,Android Atuo,Android Wear和谷歌投影设备上正常运行。这款软件对开发人员来说是一个参考设计,使他们能够了解如何实现跨多...
WD西数硬盘维修工具 Auto Trex 自动T 通刷固件 工厂固件软件。
很好,很实用,cad快捷键 各个行业都好用的快捷键,下吧。我要你们资源分
港口照片: :light_bulb:解决与错误相关的Atuo com问题。 console . log ( 'Hello World!' ) Qualificações最近的Sou Desenvolvedor,软件工程师,Aplicações,机器人(Robôs),API,插件/插件,Módulos,...
详解hibernate.hbm2ddl.atuo 属性的配置
具体实现方法如下: <!doctype html> <html> <head> <meta content=text/html; charset=GBK http-equiv=Content-Type /> <title>Image preview example</title> <style type=...
四、实验原理 基于HTML和CSS的前端开发的思想、方法,用HTML与CSS设计前端页面 五、方案设计 a:设计布局。 b:设置大盒子,大盒子中套小盒子,将大盒子划分为6个盒子。 C:最后将6个盒子里的内容进行完善 D:达到效果...