C ++中的RAII和智能指针
C++中的RAII
RAII(资源获取即初始化)是控制资源生命周期的C++技术。它是类的变体,与对象生存时间相关。
它将几种资源封装到类中,其中在对象创建期间由构造函数完成资源分配,而在对象破坏期间由析构函数完成资源释放。
保证将资源保留到对象处于活动状态。
示例
void file_write {
Static mutex m; //mutex to protect file access
lock_guard<mutex> lock(m); //lock mutex before accessing file
ofstream file("a.txt");
if (!file.is_open()) //if file is not open
throw runtime_error("unable to open file");
//写文本到文件
file << text << stdendl;
}C++中的智能指针和减号;
智能指针是一种抽象的数据类型,使用它我们可以以一种普通的指针的形式将其用作诸如文件处理,网络套接字等的内存管理,还可以执行自动销毁,引用计数等许多功能。
C++中的智能指针可以实现为模板类,并通过*和->运算符进行重载。auto_ptr,shared_ptr,unique_ptr和weak_ptr是可以由C++库实现的智能指针形式。
示例
#include <iostream>
using namespace std;
//通用智能指针类
template <class T>
class Smartpointer {
T *p; // Actual pointer
public:
//构造函数
Smartpointer(T *ptr = NULL) {
p = ptr;
}
//析构函数
~Smartpointer() {
delete(p);
}
//重载解引用运算符
T & operator * () {
return *p;
}
//重载箭头运算符,以便可以访问T的成员
//像指针
T * operator -> () {
return p;
}
};
int main() {
Smartpointer<int> p(new int());
*p = 26;
cout << "Value is: "<<*p;
return 0;
}输出结果
Value is: 26