C++中的RAII

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

什么是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)
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一苇渡江694

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值