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;
}
相关推荐
iCxhust4 小时前
c#多串口重量采集上位机程序
开发语言·汇编·c#·微机原理·8088单板机
2401_872418784 小时前
什么是多范式编程语言?——以 C++ 为例深入理解编程范式
java·大数据·c++
QK_005 小时前
volatile 关键字核心作用
开发语言
Dxy12393102165 小时前
Python Tensor 向量入门:从零理解深度学习的“数据语言“
开发语言·python·深度学习
林森lsjs5 小时前
【日耕一题】3. 通过键盘输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
java·开发语言
basketball6165 小时前
设计模式入门:3. 适配器模式详解 C++实现
c++·设计模式·适配器模式
yzy855 小时前
数据同步工具 -- syncthing
开发语言
catchadmin5 小时前
PHP 应用 security.txt 漏洞披露实践
开发语言·php
糖果店的幽灵5 小时前
LangChain 1.3 完全教程:从入门到精通-Part 11: Tools(工具系统)
开发语言·langchain·c#
夜勤月5 小时前
AQS 与 ThreadPoolExecutor 深度拆解:JDK 高并发底层设计精髓
android·java·开发语言