RAII妙用:使用标准库的包装器

使用标准库的包装器

复制代码
#include <iostream>
#include <mutex>
#include <thread>

int        x = 0;
std::mutex mutex;

void fun() {
    for (int i = 0; i < 100000; i += 1) {
        std::unique_lock<std::mutex> lock(mutex);  // RAII 自动上锁和解锁
        x += 1;
    }
}

int main() {
    std::thread th1(fun);
    std::thread th2(fun);
    th1.join();
    th2.join();
    
    std::cout << x << std::endl;
}

文件描述符的管理

文件描述符(File Descriptor) 也就是我们常说的 fd。在打开并使用后需要将其关闭。

此时有可能出现了我们上面提出的问题,如果出现了异常怎么办?如果编码时遗忘了怎么办?

此时我们就可以使用 RAII 的性质来处理。

借助智能指针的删除器

首先我们完全可以参上前面几个例子来编写一个包装类。

但这里介绍另一个技巧。借助智能指针**std::unique_ptr<>**指定的删除器来操作。

当我们指定删除器后,在智能指针析构时会调用我们指定的 lambda 表达式,此时就可以保证句柄的 close 操作。

复制代码
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <memory>

int main(int argc, char **argv) {
    int fd = open("out.txt", O_WRONLY | O_CREAT, 0666);

    if (fd == -1) {
        perror("open fail\n");
        return -1;
    }

    // 将删除器指定为一个lambda表达式
    std::unique_ptr<int, void (*)(int *)> smartFD(&fd, [](int *p) { close(*p); });

    for (int i = 0; i < argc; i += 1) {
        int len = write(fd, argv[i], strlen(argv[i]));
        if (len < 0) {
            perror("write fail\n");
            return -1;
        }
    }

    return 0;
}
相关推荐
博客18001 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴1 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨2 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4566 天前
C++进阶(1)——前景提要
c++
夜悊6 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴6 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0017 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
LDR0067 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术7 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园7 天前
C++20 Modules 模块详解
java·开发语言·spring