C++中的RAII(转)

转自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)
}
 
原文地址:https://www.cnblogs.com/wangshaowei/p/8883127.html