动态分配资源的自动释放的英文是 Resource Allocation In Initialization,通常缩写成RAII。
根据《C++ Primer》第4版:
“
During stack unwinding, the function containing the throw, 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这个类,就会造成内存泄漏:
// 测试代码
int main()
{
Student *stu = new Student("Andrew", "M", 6);
stu->printStudentInfo();
return 0;
}
因为在return之前,没有delete掉stu这个动态分配而来的资源(如果仅仅是这个程序,也没有内存泄漏之忧,因为整个应用都结束运行了,在此只是为了方便说明类似的使用方式是不可以的,即用了new动态分配了资源,而没有对应的delete去回收)。为了防止这样的方式造成的内存泄漏,上面的测试代码应该增加一行delete stu:
// 测试代码
int main()
{
Student *stu = new Student("Andrew", "M", 6); // (2)
stu->printStudentInfo();
delete stu; // (3)
return 0;
}
这样就不会造成内存泄漏了。运行该应用,输出的结果是:
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来捕获异常,代码如下:
// 测试代码
int main()
{
Student *stu = new Student("Andrew", "M", 6); // (2)
try
{
stu->printStudentInfo();
}
catch(const exception &e)
{
cout << e.what() << endl;
}
delete stu; // (3)
return 0;
}
输出结果:
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;
};
把测试代码改为:
// 测试代码
int main()
{
Student *stu = new Student("Andrew", "M", 6); // (2)
// 将stu绑定到Resource<Student>类型的res变量,res是一个local对象,当程序超出其可见范围时
// 其析构函数会自动执行。而它的析构函数中,又会自动释放stu所指向的资源
Resource<Student> res(stu);
try
{
stu->printStudentInfo();
}
catch(const runtime_error &e)
{
cout << e.what() << endl;
}
return 0;
}
上面代码的运行结果:
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。
相应的,测试代码做如下修改:
// 测试代码
int main()
{
Student *stu = new Student("Andrew", "M", 6); // (2)
// 将stu绑定到Resource<Student>类型的res变量,res是一个local对象,当程序超出其可见范围时
// 其析构函数会自动执行。而它的析构函数中,又会自动释放stu所指向的资源
Resource<Student> res(stu);
try
{
//stu->printStudentInfo(); // 这行被注释掉
res->printStudentInfo(); // 改用res来调用printStudentInfo
}
catch(const runtime_error &e)
{
cout << e.what() << endl;
}
return 0;
}
运行结果和前面是一致的,也实现了动态分配资源的自动释放。事实上,这就是大名鼎鼎的auto_ptr的实现原理。
注意,代码开始处需要包含以下语句:
#include <iostream>
#include <string>
#include <stdexcept> // 处理异常时,必须包含此头文件
using namespace std;