RAII(Resource Acquisition Is Initialization):
资源分配即初始化,定义封装一个类,用来实现调用构造函数时就可完成资源的分配和初始化,在调用析构函数就可完成资源的清理,以实现对资源的初始化和清理。
智能指针:
用自动化或者说智能的指针来实现对动态内存的释放。
它是一个类,有类似指针的功能。
常见的智能指针有:auto_ptr/scoped_ptr/scoped_array/shared_ptr/shared_array
一、AutoPtr
首先,先介绍AutoPtr,为防止一块空间释放两次浅拷贝导致的崩溃情况,我们的思想是权限转移,就是说你拷贝时要将你的两个指针指向同一块空间,可是这样会程序崩溃。解决如下:
1)老版AutoPtr
主要变量是_ptr,_owner,用bool型的_owner来控制权限转移,当它为false值时释放空间,保证释放一次。
缺陷:
出了作用域后ap2会释放空间还给系统,而ap2仍指向这块空间,会出现野指针。
2)新版AutoPtr
我们及时将之前的指针置成空,将这块空间的所有权交给现在的指针。
二、ScopedPtr
这是最实用的智能指针。
顾名思义,守卫的指针,思想就是防拷贝,在大多时候用不到拷贝构造和赋值运算符重载,那么我们做的就是写出构造函数和析构函数,拷贝构造和赋值运算符重载只声明不定义。这里有几点要说明:
(1)鉴于上面,我们写智能指针时,将拷贝构造和赋值运算符重载设置成保护或者私有的,这样就可以保证其他人在不知情的情况下(以为是我们忘记写定义了)无法写拷贝构造和赋值运算符重载的定义。
(2)既然不要定义,那为什么要声明呢,是不是可以不要,或许你们会这样想。不可以!原因是你不写,编译器会自动调用系统自身的拷贝构造和赋值运算符重载,这样就没办法做到防拷贝了。
下面,我们用ScopedPtr来实现简易版本的智能指针。
三、SharedPtr
共享指针,即思想就是引用计数,引入变量指针变量pCount,指向一块空间,对其计数,当只有一个指针指向空间时再释放资源,实现对其管理。初衷也是解决多个指针指向同一块空间释放多次会崩溃。这里不用static的整型的pCount在于,若有多个指针指向第一块空间,多个指针指向第二块空间,……,当改变一块空间的指向,该块空间的引用计数发生变化了,static的pCount会导致其他空间的引用计数也发生变化。
四、ScopedArray
ScopedArray与ScopedPtr区别在于:
ScopedArray管理数组,不可实现访问单个元素,而ScopedArray数组,可实现对数组元素的操控。
五、SharedPtr
同四。