C++中的RAII

                       

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

什么是RAII?

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

为什么需要RAII?

看一段代码:

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

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

如何使用RAII?

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

class ManagedResourceHandle {public:   ManagedResourceHandle(RawResourceHandle* rawHandle_) : rawHandle(rawHandle_) {};   ~ManagedResourceHandle() {delete rawHandle; }private:   RawResourceHandle* rawHandle;};ManagedResourceHandle handle(createNewResource());handle->performInvalidOperation();
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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

步骤:
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)}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/sfhinsc/article/details/86666481