在C/C++,我们司空见惯地甚至想当然地使用{},一般大家都认为只要 { 和 } 成对出现就可以了。诚然,{ 和 } 必须成对出现,但有些时候,尤其是在使用RAII的时候,它代表了RAII对象的作用域。关于RAII的原理说明,请见:
http://patmusing.blog.163.com/blog/static/13583496020101824142699/
参考下面代码,并注意其中的注释:
// 自动释放资源中花括号的作用
// RAII = Resource Allocation In Initialization
#include <iostream>
#include <string>
using namespace std;
// 资源类
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;
}
~Student()
{
// 下面这条语句用来提示资源是否被释放了
cout << "The destructor of class Student is called" << endl;
}
private:
string name;
string gender;
int age;
};
// 资源管理类
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; // 返回T类型的指针res
else
{
cout << "The underlying object is empty." << endl;
return 0; // 返回空指针
}
}
private:
T *res;
};
// 测试代码
int main()
{
Student *stu = new Student("Andrew", "M", 7);
// 测试块语句
// 下面是一个块语句,亦称符合语句,可以将它看成一个语句。
{
Resource<Student> res(stu); // res是一个local对象,其作用域在{}之间,
res->printStudentInfo(); // 程序运行超出了{},那么res将会被自动
cout << "HIHI:" << endl; // 析构
}
cout << "HOHO" << endl;
return 0;
}
输出结果:
Name: Andrew Gender: M Age: 7
HIHI:
The destructor of class Student is called
Resources are deallocated here.
HOHO
从上面输出的结果可知,res只在花括号内存在,一旦程序运行超出了花括号,res对应的析构函数将会被自动执行,同时由于在res内部有delete stu;这样的语句,因此stu所指的对象也会因此被自动析构。