有很多东西我们一直在用,但是不知道他的名字。
什么是RAII?
RAII是Resource Acquisition Is Initialization的缩写,用普通话将就是”资源获取即初始化”
为什么需要RAII?
看一段代码:
RawResourceHandle* handle=createNewResource(); handle->performInvalidOperation(); // 发生异常 ... deleteResource(handle); // 永远不会释放
如何使用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
#include
#include
#include
#include
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://javaforall.net/220430.html原文链接:https://javaforall.net
