`
阿尔萨斯
  • 浏览: 4180372 次
社区版块
存档分类
最新评论

c++ atuo_ptr 的实现原理

 
阅读更多

偶尔在一本书上看到了称为智能指针的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之前,没有deletestu这个动态分配而来的资源(如果仅仅是这个程序,也没有内存泄漏之忧,因为整个应用都结束运行了,在此只是为了方便说明类似的使用方式是不可以的,即用了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

弱引用指针


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics