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;
}
相关推荐
科技道人18 分钟前
记录 默认置灰/禁用 app ‘Search Engine Selector‘ 的disable按钮
开发语言·前端·javascript
逝水无殇3 小时前
C# 异常处理详解
开发语言·后端·c#
旖-旎4 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
玖玥拾4 小时前
C# 语言进阶(十五)C# 游戏服务端 MySQL 数据库
服务器·开发语言·网络·数据库·mysql·c#
铅笔侠_小龙虾4 小时前
Rust 学习目录
开发语言·学习·rust
Darkwanderor5 小时前
对Linux的进程控制的研究
linux·运维·c++
云泽8085 小时前
从零吃透 C++ 异常:抛出捕获、栈展开、异常重抛与编码规范详解
开发语言·c++·代码规范
灯澜忆梦5 小时前
GO---可见性规则
开发语言·golang
REDcker5 小时前
libdatachannel 快速入门
c++·webrtc·datachannel
逝水无殇5 小时前
C# 文件的输入与输出详解
开发语言·数据库·后端·c#