转自https://blog.csdn.net/wangshubo1989/article/details/52133213

有很多东西我们一直在用,但是不知道他的名字。

什么是RAII?

RAII是Resource Acquisition Is Initialization的缩写,用普通话将就是”资源获取即初始化”

为什么需要RAII?

看一段代码:

RawResourceHandle* handle=createNewResource();
handle->performInvalidOperation(); // 发生异常
...
deleteResource(handle); // 永远不会释放

上面的代码所示是常见的内存泄露。更多的时候,我们使用C++11中的智能指针来解决上面的问题。 
但是,如果不使用智能指针,那么是不是就是轮到RAII出场了。

如何使用RAII?

最简单的说,就是进行一个简单的封装:

class ManagedResourceHandle {
public:
ManagedResourceHandle(RawResourceHandle* rawHandle_) : rawHandle(rawHandle_) {};
~ManagedResourceHandle() {delete rawHandle; }
private:
RawResourceHandle* rawHandle;
}; ManagedResourceHandle handle(createNewResource());
handle->performInvalidOperation();

有了上面代码中的封装,就不需要担心产生异常了。

步骤: 
1 Encapsulate a resource into a class

2 Use the resource via a local instance of the class*

3 The resource is automatically freed when the object gets out of scope

RAII与C++11

写一个write to file的函数:

#include <mutex>
#include <iostream>
#include <string>
#include <fstream>
#include <stdexcept> void write_to_file (const std::string & message) {
// mutex to protect file access (shared across threads)
static std::mutex mutex; // lock mutex before accessing file
std::lock_guard<std::mutex> lock(mutex); // try to open file
std::ofstream file("example.txt");
if (!file.is_open())
throw std::runtime_error("unable to open file"); // write message to file
file << message << std::endl; // file will be closed 1st when leaving scope (regardless of exception)
// mutex will be unlocked 2nd (from lock destructor) when leaving
// scope (regardless of exception)
}
 

C++中的RAII(转)的更多相关文章

  1. C++中的RAII机制

    http://www.jellythink.com/archives/101 前言 在写C++设计模式——单例模式的时候,在写到实例销毁时,设计的GC类是很巧妙的,而这一巧妙的设计就是根据当对象的生命 ...

  2. C++中的RAII介绍 资源管理

    摘要 RAII技术被认为是C++中管理资源的最佳方法,进一步引申,使用RAII技术也可以实现安全.简洁的状态管理,编写出优雅的异常安全的代码. 资源管理 RAII是C++的发明者Bjarne Stro ...

  3. C++中的RAII介绍

    摘要 RAII技术被认为是C++中管理资源的最佳方法,进一步引申,使用RAII技术也可以实现安全.简洁的状态管理,编写出优雅的异常安全的代码. 资源管理 RAII是C++的发明者Bjarne Stro ...

  4. C++中的RAII技法

    Resource Acquisition Is Initialization or RAII, is a C++ programming technique which binds the life ...

  5. C++中的初始化

    C++中的RAII机制指明”对象创建时通过构造函数进行初始化,析构时通过析构函数释放资源”,但实际中因类无构造函数时编译器将自动合成一个默认构造函数,该构造函数只服务于自身编译器构造需要而不负责对象成 ...

  6. Linux组件封装(四)使用RAII技术实现MutexLock自动化解锁

    我们不止一次写过这种代码: { mutex_.lock(); //XXX if(....) return; //XXX mutex_.unlock(); } 显然,这段代码中我们忘记了解锁.那么如何防 ...

  7. C++之RAII惯用法

    http://blog.csdn.net/hunter8777/article/details/6327704 C++中的RAII全称是“Resource acquisition is initial ...

  8. C++ 中的智能指针-基础

    简介 在现代 C++ 编程中,标准库包含了智能指针(Smart pointers). 智能指针用来确保程序不会出现内存和资源的泄漏,并且是"异常安全"(exception-safe ...

  9. 面向对象编程(C++篇4)——RAII

    目录 1. 概述 2. 详论 2.1. 堆.栈.静态区 2.2. 手动管理资源的弊端 2.3. 间接使用 2.4. 自下而上的抽象 3. 总结 4. 参考 1. 概述 在前面两篇文章<面向对象编 ...

随机推荐

  1. Linux按键设备驱动一

    ① request_irq函数用于注册中断 int request_irq(unsigned int irq, void(*handler)(int, void*, struct pt_reg*), ...

  2. CentOS6 克 隆

    原始机子关机 自己设置名字 保存地址 开机 配置hosts   后面的为你要设置的名字不配置可能xshell链接上不了网 更改名字: 配置网卡 删除物理地址 mac 和  uuid 删除网卡 重启

  3. How to install local .deb packages

    如何安装本地的.deb包 usually I do dpkg -i <deb file>, it'll fail saying it needs dependencies. After t ...

  4. linux_api之进程环境(二)

      本篇索引: 1.引言 2.终端登录 3.进程组 4.会话期 1.引言 通过上一篇的学习,我们已经知道了如何控制一个进程,fork函数从父进程中复制出子进程,我们可以通过exec函数让子进程运行新的 ...

  5. TreeMap和TreeSet简单应用

    建一个实体类并实现Comparable接口重写compareTo方法 public class pojo implements Comparable<pojo> { private int ...

  6. React.js 小书 Lesson13 - 渲染列表数据

    作者:胡子大哈 原文链接:http://huziketang.com/books/react/lesson13 转载请注明出处,保留原文链接和作者信息. 列表数据在前端非常常见,我们经常要处理这种类型 ...

  7. flask表单flask-wtf

    一.安装pip install flask-wtf 二.创建一个flask的项目引入相对应的包 from flask import Flask,render_template import flask ...

  8. go语言中文处理

    中文在go语言中占三个字节,len 或者 range 一个含中文的字符串跟我们预期的结果不一样 求长度用 utf8.RuneCountInString,遍历用 rune func main() { t ...

  9. openlayers 聚合效果

    //cyd var cydclusterSource = new ol.source.Cluster({ distance: 40, source: new ol.source.Vector({ fe ...

  10. hibernate open session in view 抛出异常解决方法

    在使用open-session-in-view的时候,如果使用不当,有可能抛出两种异常1,NonUniqueObjectException2,在配合spring使用的时候会可能会抛出org.sprin ...