使用标准库的包装器
#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;
}