输入输出、文件操作与 C 标准库
读写数据是每个程序的基本功。这篇先讲 C++ 的流体系(iostream):cin/cout 为什么比 scanf 安全、流状态位怎么查、文件怎么开、二进制怎么写、stringstream 为什么是解析神器、chrono 怎么处理时间。后半篇系统过一遍 C 标准库——和 C 代码交互、维护遗留代码、面试时都能用上。
一、C++ 流体系
1.1 层次结构
ios_base ← 格式标志、流状态
├── basic_ios ← 关联 streambuf
│ ├── basic_istream ← 输入操作(>>, get, getline)
│ └── basic_ostream ← 输出操作(<<, put, flush)
│ └── basic_iostream(继承两者)
├── basic_ifstream ← 文件输入
├── basic_ofstream ← 文件输出
├── basic_fstream ← 文件读写
├── basic_istringstream ← 字符串输入
└── basic_ostringstream ← 字符串输出char 特化就是日常用的名字:istream ostream ifstream istringstream……宽字符版是 wistream 等。所有流共享同一套操作接口——这是「流」抽象的价值:写一份输出代码,目标可以是终端、文件、内存字符串。
1.2 标准输入输出
#include <iostream>
int x;
std::cin >> x; // 读一个 int,跳过前导空白
std::cout << "value: " << x << '\n'; // 输出;'\n' 比 std::endl 快(不 flush)
std::cerr << "error\n"; // 无缓冲错误流,立即输出
std::clog << "log\n"; // 有缓冲日志流>> 的坑:
int n;
std::cin >> n; // 用户输入 "12abc" → n=12,'a' 留在缓冲区
char c;
std::cin >> c; // c = 'a',不是你以为的重新读
std::string line;
std::getline(std::cin, line); // 读一整行(不含 '\n')
// 混合 >> 和 getline 的经典 bug:>> 留下的 '\n' 被 getline 吃掉,第一行变空串
std::cin >> n;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 清掉行尾
std::getline(std::cin, line);cin 读失败时流进入 fail 状态,后续所有读取直接跳过——不检查状态的死循环是输入题挂掉的头号原因:
while (std::cin >> n) { use(n); } // 失败即退出,最简形式
// 或显式:
while (true) {
if (!(std::cin >> n)) break; // EOF 或非数字
use(n);
}1.3 流状态
四个状态位(ios::goodbit eofbit failbit badbit):
if (std::cin.good()) { } // 一切正常
if (std::cin.eof()) { } // 读到文件尾
if (std::cin.fail()) { } // 类型转换失败等可恢复错误
if (std::cin.bad()) { } // 流损坏(硬件错误)
int n;
if (std::cin >> n) { // 隐式转 bool:!fail(),最常用
use(n);
} else {
std::cin.clear(); // 清状态,还能继续用
std::cin.ignore(...); // 跳过脏数据
}eof 和 fail 一起出现是常态:读到文件尾时,最后一次读触发 eofbit 和 failbit。判断「读完了」用 while (cin >> x),不要单独 eof()——eof() 只在「尝试读过尾之后」才真。
1.4 格式化输出
#include <iomanip>
std::cout << std::setw(10) << 42 << '\n'; // 右对齐占 10 列
std::cout << std::setfill('0') << std::setw(8) << 42 << '\n'; // 00000042
std::cout << std::left << std::setw(10) << 42 << '\n';// 左对齐
std::cout << std::hex << 255 << '\n'; // ff
std::cout << std::oct << 8 << '\n'; // 10
std::cout << std::dec << 255 << '\n'; // 255
std::cout << std::fixed << std::setprecision(2) << 3.14159 << '\n'; // 3.14
std::cout << std::scientific << 12345.678 << '\n'; // 1.23e+04
std::cout << std::boolalpha << true << '\n'; // true(不是 1)注意流格式是「粘性」的——设了 hex 后面所有整数都按十六进制输出,用完记得 std::dec 恢复。对齐表格的完整套路:
for (const auto& row : rows) {
std::cout << std::left << std::setw(12) << row.name
<< std::right << std::setw(6) << row.age << '\n';
}需要一次性格式(不污染流状态)用 C++20 的 std::format:std::format("{:>10}", 42)——Python f-string 风格,编译期检查格式串。
二、文件流
2.1 打开与模式
#include <fstream>
// 写文件
std::ofstream ofs("out.txt"); // 默认 out|trunc:清空重写
ofs << "hello\n";
// 追加
std::ofstream ofs2("log.txt", std::ios::app);
ofs2 << "new line\n";
// 读文件
std::ifstream ifs("in.txt");
std::string line;
while (std::getline(ifs, line)) { process(line); }
// 读写
std::fstream fs("data.bin", std::ios::in | std::ios::out | std::ios::binary);打开模式标志:
| 标志 | 作用 |
|---|---|
ios::in | 读(ifstream 默认) |
ios::out | 写(ofstream 默认) |
ios::app | 追加:写之前总 seek 到文件尾 |
ios::trunc | 打开时清空(默认) |
ios::ate | 打开时定位到文件尾(之后可 seek 回去) |
ios::binary | 二进制模式,不做换行转换 |
打开失败不抛异常——ifstream 对象转 bool 为假,或检查 is_open():
std::ifstream ifs("config.txt");
if (!ifs) {
std::cerr << "cannot open config.txt: " << std::strerror(errno) << '\n';
return 1;
}exceptions() 可以让流在失败时抛 ios_base::failure(C++11 起自带 what() 说明):
ifs.exceptions(std::ios::failbit); // failbit 置位即抛2.2 文本读写与二进制读写
// 文本:getline 逐行
std::ifstream ifs("data.txt");
std::vector<std::string> lines;
std::string line;
while (std::getline(ifs, line)) lines.push_back(line);
// 二进制:read/write 直接操作内存块
struct Record { int id; double value; char name[16]; };
std::ofstream ofs("data.bin", std::ios::binary);
Record r{1, 3.14, "hello"};
ofs.write(reinterpret_cast<const char*>(&r), sizeof(r)); // 写裸内存
std::ifstream ifs2("data.bin", std::ios::binary);
Record r2;
ifs2.read(reinterpret_cast<char*>(&r2), sizeof(r2));Windows 文本模式陷阱:文本模式下 \n 被转成 \r\n 写出,读时转回。二进制文件(图片、序列化结构体)必须 ios::binary,否则数据被静默改写,文件大小也错。Linux/macOS 无此转换,所以这个 bug 只在 Windows 冒出来——跨平台项目的经典「为什么我电脑上好的」。
二进制写结构体的隐患:直接 dump 内存意味着结构体 padding、成员对齐、指针成员、int 宽度全部固化进文件——换编译器/平台读不出来。生产环境用序列化库(protobuf、flatbuffers、MessagePack)或逐字段按定宽类型读写。
2.3 文件定位
ofs.tellp(); // 当前写位置
ofs.seekp(0, std::ios::end); // 定位到文件尾
ofs.seekp(100, std::ios::beg); // 从头偏移 100
ifs.seekg(-4, std::ios::cur); // 从当前位置回退 4
ifs.seekg(0, std::ios::end);
size_t size = ifs.tellg(); // 求文件大小的惯用法
ifs.seekg(0, std::ios::beg);2.4 一次读完整个文件
std::ifstream ifs("data.txt");
std::string content((std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());流迭代器 + 字符串构造,无需知道文件大小。
2.5 filesystem(C++17)
#include <filesystem>
namespace fs = std::filesystem;
if (fs::exists("a.txt")) { }
auto size = fs::file_size("a.txt");
fs::copy_file("a.txt", "b.txt");
fs::create_directory("logs");
fs::remove("tmp.txt");
for (const auto& entry : fs::directory_iterator("src")) {
std::cout << entry.path() << '\n';
}
for (const auto& entry : fs::recursive_directory_iterator(".")) {
if (entry.is_regular_file() && entry.path().extension() == ".cpp") {
total += entry.file_size();
}
}注意 filesystem 在不同编译器上的链接要求:GCC 8 以前需要 -lstdc++fs,MSVC C++17 模式直接可用。路径分隔符用 entry.path() 自动处理,不要手拼 \\ 或 /。
三、字符串流:解析与格式化神器
stringstream 把内存字符串伪装成流——输入流用来解析,输出流用来拼字符串:
#include <sstream>
// 解析:CSV 行拆字段
std::string line = "alice,90,beijing";
std::istringstream iss(line);
std::string name, city;
int score;
std::getline(iss, name, ',');
iss >> score;
iss.ignore(1);
std::getline(iss, city);
// 解析混合内容:数字 + 单位
std::istringstream iss2("1024 bytes");
int n; std::string unit;
iss2 >> n >> unit; // n=1024, unit="bytes"
// 格式化:避免 + 拼接地狱
std::ostringstream oss;
oss << "id=" << id << ",price=" << std::fixed << std::setprecision(2) << price;
std::string result = oss.str();
// 类型安全转换(C++11 起可直接用 stoi 等)
std::istringstream iss3("42");
int v; iss3 >> v;
if (iss3.fail()) { /* 不是数字 */ }字符串流的典型场景:配置文件解析、日志格式化、协议编解码、单测里模拟输入流。比 printf 类型安全,比 + 拼接可读。
四、日期与时间
4.1 chrono 三件套(C++11)
#include <chrono>
#include <thread>
// duration:一段时间,编译期单位
std::chrono::seconds s1(30);
std::chrono::milliseconds ms(500);
auto total_ms = s1 + ms; // 自动换算成毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// time_point:一个时刻
auto start = std::chrono::steady_clock::now();
do_work();
auto end = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "took " << elapsed.count() << " ms\n";
// 时钟类型
std::chrono::system_clock::now(); // 系统挂钟时间,可转 time_t
std::chrono::steady_clock::now(); // 单调递增,不受改表影响——测间隔用它
std::chrono::high_resolution_clock::now(); // 最高精度(通常是 steady 的别名)测时间必须用 steady_clock:system_clock 会被 NTP 校准、用户改表影响,可能出现「代码跑出负耗时」的灵异事件。
4.2 常用字面量与转换
using namespace std::chrono_literals; // C++14
auto timeout = 500ms;
auto interval = 2s;
auto now = std::chrono::system_clock::now();
std::time_t t = std::chrono::system_clock::to_time_t(now); // chrono → time_t
std::tm* local = std::localtime(&t);
std::cout << std::put_time(local, "%Y-%m-%d %H:%M:%S"); // 需要 <iomanip>C++20 的 chrono 日历扩展补齐了最后短板——直接操作日期而不是秒数:
// C++20 <chrono>
auto today = std::chrono::floor<std::chrono::days>(std::chrono::system_clock::now());
std::chrono::year_month_day ymd{today};
ymd.year(); ymd.month(); ymd.day(); // 2026y/10/23
auto d = 2026y/10/1; // 日期字面量
d + std::chrono::months(1); // 日期加减,自动处理大小月4.3 与 C time.h 互操作
老代码和 C API 用 time_t(秒数)+ struct tm(分解时间)。对应表:
| C | C++ chrono |
|---|---|
time_t | system_clock::to_time_t 可互换 |
clock() | steady_clock 测 CPU/墙钟 |
struct tm | std::chrono::year_month_day(C++20) |
strftime | std::format/std::put_time |
五、C 标准库总览
C++ 完全包含 C 标准库(头文件名改为 c 前缀形式,如 <cstdio>,旧名 <stdio.h> 仍可用)。按功能分组:
| 头文件 | 内容 | 本篇章节 |
|---|---|---|
stdio.h | 标准输入输出、文件操作 | 六 |
string.h | 字符串与内存块操作 | 七 |
ctype.h | 字符分类 | 八 |
math.h | 数学函数 | 九 |
stdlib.h | 内存分配、转换、工具、随机数 | 十 |
time.h | 时间日期 | 四 |
assert.h | 断言 | 十一 |
limits.h / float.h | 类型常数 | 十一 |
stdarg.h | 变长参数 | 十二 |
setjmp.h | 非局部跳转 | 十三 |
六、stdio.h:标准输入输出与文件
6.1 格式化 I/O
#include <cstdio>
int n = 42;
double pi = 3.14159;
std::printf("n=%d, hex=%x, pi=%.2f\n", n, n, pi); // 输出
std::printf("%10d|%-10d|%05d\n", 42, 42, 42); // 右对齐/左对齐/补零
char buf[64];
std::snprintf(buf, sizeof(buf), "id=%d", n); // 安全版 sprintf(C++11 起可用)
// std::sprintf(buf, ...); // 不安全:不检查容量,禁用
int x;
if (std::sscanf("42 abc", "%d", &x) == 1) { } // 输入解析,返回成功项数常用格式符:%d/%i(int)、%u(无符号)、%ld(long)、%lld(long long,C++11 起标准)、%f/%g/%e(浮点)、%c(字符)、%s(字符串)、%p(指针)、%%(百分号)、%zu(size_t)。
scanf 的坑:%s 不检查缓冲区长度(用 %15s 限宽);返回的赋值个数必须检查(失败时变量未定义);%d 遇到非数字停住但字符留在缓冲区——和 cin 一个毛病。C++ 代码优先 cin/stringstream,scanf 只在解析超大数据(竞速题)或 C API 交互时用。
6.2 文件操作
#include <cstdio>
std::FILE* f = std::fopen("data.txt", "r"); // r/w/a/r+/w+/a+/rb/wb/ab
if (!f) { perror("fopen"); return 1; } // perror 打印 errno 对应的信息
// 读
char line[256];
while (std::fgets(line, sizeof(line), f)) { // 安全读一行(带容量)
// line 含 '\n'
}
int ch;
while ((ch = std::fgetc(f)) != EOF) { } // 逐字符读
// 写
std::fputs("hello\n", f); // 写字符串
std::fprintf(f, "value=%d\n", 42); // 格式化写
// 二进制块读写
Record rec;
std::fread(&rec, sizeof(Record), 1, f); // 读 1 条记录
std::fwrite(&rec, sizeof(Record), 1, f); // 写 1 条记录
// 定位
std::fseek(f, 0, SEEK_SET); // 文件头
std::fseek(f, -10L, SEEK_END); // 文件尾前 10
long pos = std::ftell(f); // 当前位置
std::rewind(f); // 回到文件头
// 关闭(必须!否则数据可能不落盘、句柄泄漏)
std::fclose(f);fread/fwrite 返回读写的元素个数,必须检查:
if (std::fread(&rec, sizeof(Record), 1, f) != 1) {
if (std::feof(f)) { /* 正常到文件尾 */ }
else if (std::ferror(f)) { /* 读错误 */ }
}fclose 前想强制落盘用 std::fflush(f)(对输入流是未定义行为,对输出流把缓冲区写入文件)。关闭文件、检查返回值:磁盘满时 fclose 也可能失败,日志系统栽在这里的不少。
七、string.h:字符串与内存操作
#include <cstring>
// 长度与拷贝
size_t len = std::strlen("hello"); // 5,O(n)
char dst[16];
std::strcpy(dst, "hello"); // 不含边界检查!
std::strncpy(dst, "hello", sizeof(dst) - 1); // 限长版,可能不补 '\0'
dst[sizeof(dst) - 1] = '\0'; // 手动保证终止
// 拼接
std::strcat(dst, " world"); // 拼到 dst 尾部
std::strncat(dst, "!", sizeof(dst) - strlen(dst) - 1);
// 比较与查找
std::strcmp("abc", "abd"); // <0,逐字节比
std::strncmp("abc", "abd", 2); // ==0,只比前 2 字节
const char* p = std::strstr("hello world", "world"); // 找子串,返回指针
const char* q = std::strchr("hello", 'l'); // 找字符
const char* r = std::strtok(buf, " ,."); // 分词(破坏原串,非线程安全)
// 内存块操作(可含 '\0',用于任意二进制数据)
std::memcpy(dst, src, n); // 不处理重叠,快
std::memmove(dst, src, n); // 处理重叠,稍慢
std::memset(buf, 0, sizeof(buf)); // 清零
int cmp = std::memcmp(a, b, n); // 按字节比较memcpy 重叠即 UB:源和目标区间重叠时必须用 memmove。memcpy 允许假设不重叠,编译器可能做向量化重排,结果错乱。
所有字符串函数的共同前提:目标缓冲区足够大。strcpy/strcat 系列是 C 的历史包袱,C11 的 strcpy_s/strcat_s(Annex K)是官方补丁但实现支持不一(MSVC 支持,GCC 长期没有)。可移植做法:snprintf(dst, sizeof(dst), "%s%s", a, b)——格式化的同时保证截断。
八、ctype.h:字符分类
#include <cctype>
char c = '7';
std::isdigit(c); // 是否 0-9
std::isalpha(c); // 是否字母
std::isalnum(c); // 字母或数字
std::isspace(c); // 空白(空格 \t \n \r \f \v)
std::isupper(c); std::islower(c);
std::toupper(c); // 转大写(返回 int,赋回要截 char)
std::tolower(c);
std::isxdigit(c); // 是否十六进制数字
std::ispunct(c); // 是否标点两个坑:
- 参数必须是可表示为
unsigned char的值或EOF。传负的char(比如char有符号时的中文编码字节)是 UB——std::tolower((unsigned char)c)才是安全写法。 - 只对 ASCII 定义。中文标点、全角空格别用这套。
九、math.h:数学函数
#include <cmath>
std::abs(-5); // 整数绝对值(<cstdlib> 也有)
std::fabs(-3.14); // 浮点绝对值
std::sqrt(2.0); // 平方根(负参数得 NaN,不抛异常)
std::pow(2.0, 10.0); // 幂,1024
std::exp(1.0); std::log(10.0); // e^x、自然对数
std::log2(8.0); // 3(C++11)
std::sin(0.0); std::cos(0.0); std::tan(0.0);
std::floor(3.7); std::ceil(3.2); std::round(3.5); // 3, 4, 4
std::fmod(10.0, 3.0); // 浮点取余:1.0
std::hypot(3.0, 4.0); // 斜边:5.0(比 sqrt(x*x+y*y) 防溢出)
// 分类(C++11)
std::isnan(0.0/0.0); // 是否 NaN
std::isinf(1.0/0.0); // 是否无穷
std::isfinite(1.0); // 是否有限浮点比较永远带误差:
bool almost_equal(double a, double b, double eps = 1e-9) {
return std::fabs(a - b) <= eps * std::max(1.0, std::fmax(std::fabs(a), std::fabs(b)));
}sqrt(-1) 得 NaN、log(0) 得 -inf,同时设 errno = EDOM——默认不抛。要错误处理可以传第二个参数或用 std::fetestexcept。三角函数参数是弧度不是角度:sin(30 * M_PI / 180)。
十、stdlib.h:内存、转换与工具
10.1 动态内存
#include <cstdlib>
int* p = static_cast<int*>(std::malloc(100 * sizeof(int))); // 分配,不初始化
if (!p) { /* 失败返回 nullptr */ }
std::free(p); // 必须配 malloc/calloc/realloc
int* z = static_cast<int*>(std::calloc(100, sizeof(int))); // 分配并清零
int* bigger = static_cast<int*>(std::realloc(p, 200 * sizeof(int))); // 扩容(可能搬家)
if (!bigger) { /* realloc 失败:原 p 仍有效,不要覆盖 */ }
p = bigger;realloc 失败时返回空但原块仍有效——所以先存临时变量,失败时还能用旧指针释放。别把 realloc 结果直接赋回原指针(失败就丢了唯一引用,泄漏)。
10.2 格式转换
std::atoi("42"); // int,失败返回 0(无法区分 "0" 和非法)
std::atof("3.14");
std::strtol("42abc", &end, 10); // long,end 指向第一个无效字符——能检查!
std::strtod("3.14xyz", &end);
std::strtoul("0xFF", nullptr, 16); // 255,按 16 进制解析
int errno_saved = errno;
long v = std::strtol(s, &end, 10);
if (*end != '\0' || end == s) { /* 不是合法数字 */ }
if (errno == ERANGE) { /* 溢出 */ }atoi 家族没有错误报告,一律用 strtol/strtod + errno 检查。
10.3 搜索与排序
#include <cstdlib>
int cmp(const void* a, const void* b) { // qsort 比较器:void* 参数
return *(static_cast<const int*>(a)) - *(static_cast<const int*>(b)); // 注意溢出
}
int arr[] = {3, 1, 2};
std::qsort(arr, 3, sizeof(int), cmp); // 原地排序,O(n log n)
int key = 2;
int* found = static_cast<int*>(std::bsearch(&key, arr, 3, sizeof(int), cmp));qsort/bsearch 是 C 接口:比较器收 const void*、返回 int,类型不安全(传错 sizeof 直接内存错乱)。C++ 代码用 std::sort/std::binary_search——类型安全、快得多(可内联比较器)。
10.4 随机数
std::srand(static_cast<unsigned>(std::time(nullptr))); // 播种(一次)
int r = std::rand(); // 0 ~ RAND_MAX(通常 2147483647)
int dice = std::rand() % 6 + 1; // 1~6,但有模偏差
int range = std::rand() % 100 + 1;rand 质量差、% 有模偏差、全局状态非线程安全。C++11 起用 <random>:
#include <random>
std::random_device rd;
std::mt19937 gen(rd()); // 梅森旋转,32 位
std::uniform_int_distribution<int> dist(1, 6);
int dice = dist(gen); // 无偏差的 1~6
std::uniform_real_distribution<double> real01(0.0, 1.0);10.5 进程控制
std::exit(EXIT_SUCCESS); // 正常退出:调用 atexit 注册的函数 + 析构静态对象
std::exit(EXIT_FAILURE);
std::abort(); // 异常终止:不清理,可能产生 core dump
int code = std::atexit(cleanup); // 注册退出回调
const char* home = std::getenv("HOME"); // 读环境变量
int rc = std::system("ls -l"); // 执行 shell 命令,返回退出状态std::abort() 不调用析构——锁可能不释放、文件不 flush。只在「已经无法体面收场」时用。std::system 有注入风险和平台差异,生产代码避免。
十一、assert.h 与类型常数
11.1 断言
#include <cassert>
assert(ptr != nullptr); // 条件为假:打印信息并 abort
assert(i >= 0 && i < size);assert 是调试工具不是错误处理:条件失败会立即 abort,且 NDEBUG 宏定义时全部消失。因此:
- 用它查「绝不该发生」的内部逻辑错误。
- 不要用它检查用户输入、文件不存在这类可恢复错误——那是异常/错误码的职责。
assert里的表达式不能有副作用:assert(++i < 10)在 Release 下i不增加。- 失败信息含文件名、行号、条件文本,比裸
abort好定位。
11.2 类型常数
C 风格(<climits>/<cfloat>,即 C 的 limits.h/float.h):
INT_MAX; INT_MIN; UINT_MAX; LONG_MAX; LLONG_MIN; // 整型
CHAR_BIT; // 8
DBL_MAX; DBL_MIN; DBL_EPSILON; FLT_MAX; // 浮点C++ 风格(<limits>,首选):
std::numeric_limits<int>::max();
std::numeric_limits<int>::is_signed;
std::numeric_limits<double>::epsilon(); // 机器精度
std::numeric_limits<double>::infinity();
std::numeric_limits<int>::digits10; // 有效十进制位数std::numeric_limits 是模板、有类型、可重载,写泛型代码(「这个 T 的最大值是多少」)只能用它。
十二、stdarg.h:变长参数
实现自己的 printf 风格函数:
#include <cstdarg>
#include <cstdio>
double average(int count, ...) {
va_list args;
va_start(args, count); // 从最后一个命名参数开始
double sum = 0;
for (int i = 0; i < count; ++i) {
sum += va_arg(args, double); // 按实际类型取——取错类型是 UB
}
va_end(args); // 必须调用
return sum / count;
}
average(3, 1.0, 2.0, 3.0); // 2.0铁律:
- 至少一个命名参数,
va_start靠它定位。 va_arg的「类型」必须和实参提升后的类型一致(float提升为double,小整型提升为int)。取float是经典错误。- 参数个数无法从
va_list得知——靠命名参数传 count(average)或格式串解析(printf)。 va_end必须调,va_list不能复用(需要两次遍历就va_copy)。- 没有类型安全:
average(3, 1.0, 2, 3)会把int当double读,结果垃圾。
C++ 里变长参数的现代替代:initializer_list(f({1, 2, 3}))、可变参数模板(f(1, 2.0, "x"),类型安全)。只有对接 C API(printf 系列)才必须手写 va_list。
十三、setjmp.h:非局部跳转
#include <csetjmp>
jmp_buf env;
void deep_function() {
if (error) {
std::longjmp(env, 1); // 跳回 setjmp 处,返回值为 1
}
}
int main() {
int code = std::setjmp(env); // 保存现场;longjmp 后从这里「返回」,code = 1
if (code == 0) {
deep_function(); // 正常路径
} else {
// 错误路径
}
}C++ 中基本绝迹,因为 longjmp 跳过栈展开:C++ 对象的析构函数不会执行——锁不释放、内存泄漏,比 C 里危险得多。标准明确说「longjmp 越过带有非平凡析构的自动对象是 UB」。
唯一还在用的场景:C 库的错误处理回调链(比如某些解析器库),且绝不跨越 C++ 代码边界。新代码用异常。
相关阅读
- 《异常处理与内存管理》—— C++ 的错误处理与资源管理
- 《多线程与并发编程》—— 线程安全的 I/O
- 《现代 C++:C++11/14/17/20 新特性》—— format 等新 IO 特性
