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;
}
相关推荐
隐积3 小时前
3.1.7.Qt容器大家族(3):QVariant——万能盒子
开发语言·qt
Tri_Function5 小时前
动态规划DP1(c++)
c++
名字还没想好☜6 小时前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
初级代码游戏7 小时前
iOS开发 Swift 速记1:变量和基本数据类型
开发语言·ios·swift
酷在前行7 小时前
【R生态】PERMANOVA 进阶实战:距离选择、PERMDISP、两两比较与受限置换(保姆级教程)
开发语言·r语言
cxr8288 小时前
Graphify vs GitNexus vs CodeGraph — 三工具架构深度对比
开发语言·架构·知识图谱
清水迎朝阳8 小时前
客户端软件 — 用户统计方案
服务器·c++·客户端·用户统计
废弃的小码农9 小时前
功能测试--Day07--Python编程基础
开发语言·python
再卷也是菜9 小时前
C++17(下)
c++
fengci.9 小时前
Microweber CMS 未授权路径穿越漏洞(CVE-2026-65694)
android·开发语言·前端·学习·php