std::stacktrace(C++23)
什么是 std::stacktrace
std::stacktrace 是 C++23 引入的标准库组件,定义在 <stacktrace> 头文件中。它能在运行时捕获当前的调用栈信息,包括每一帧的函数名、源文件和行号。
在 C++23 之前,获取调用栈需要依赖平台特定的 API(如 Linux 的 backtrace()、Windows 的 CaptureStackBackTrace())或第三方库(如 Boost.Stacktrace)。现在标准库提供了统一的、跨平台的方式。
cpp
#include <stacktrace>
#include <iostream>
void foo() {
// 捕获当前调用栈
auto trace = std::stacktrace::current();
std::cout << trace << std::endl;
}核心类型
| 类型 | 说明 |
|---|---|
std::stacktrace_entry | 单个栈帧,包含函数名、文件名、行号等 |
std::basic_stacktrace<Alloc> | 栈帧集合,存储完整调用栈 |
std::stacktrace | basic_stacktrace<std::allocator<stacktrace_entry>> 的别名 |
stacktrace_entry 的成员
| 成员 | 说明 |
|---|---|
description() | 返回栈帧的描述(通常是函数名) |
source_file() | 返回源文件名 |
source_line() | 返回行号 |
native_handle() | 返回平台特定的句柄 |
operator bool() | 判断栈帧是否有效 |
basic_stacktrace 的成员
| 成员 | 说明 |
|---|---|
current() | 静态函数,捕获当前调用栈 |
current(skip) | 跳过前 skip 帧 |
current(skip, max) | 跳过前 skip 帧,最多捕获 max 帧 |
size() | 栈帧数量 |
empty() | 是否为空 |
operator[] | 访问特定帧 |
begin() / end() | 迭代器 |
基本示例
cpp
#include <iostream>
#include <stacktrace>
#include <string>
#include <stdexcept>
#include <format>
// ============================
// 示例1:打印当前调用栈
// ============================
void inner_function() {
// 捕获当前完整的调用栈
auto trace = std::stacktrace::current();
// 直接输出(重载了 operator<<)
std::cout << "当前调用栈:" << std::endl;
std::cout << trace << std::endl;
}
void middle_function() {
inner_function();
}
void stack_demo() {
middle_function();
}
// ============================
// 示例2:逐帧访问
// ============================
void frame_access_demo() {
auto trace = std::stacktrace::current();
std::cout << "栈帧数量: " << trace.size() << std::endl;
for (size_t i = 0; i < trace.size(); i++) {
const auto& entry = trace[i];
std::cout << " 帧 " << i << ":" << std::endl;
std::cout << " 函数: " << entry.description() << std::endl;
std::cout << " 文件: " << entry.source_file() << std::endl;
std::cout << " 行号: " << entry.source_line() << std::endl;
}
}
// ============================
// 示例3:跳过帧
// ============================
void log_trace(const std::string& msg,
std::stacktrace trace = std::stacktrace::current()) {
// 使用默认参数,trace 在调用者处捕获
std::cout << msg << std::endl;
std::cout << trace << std::endl;
}
void skip_demo() {
// 方式1:使用默认参数(推荐)
log_trace("调用栈(默认参数方式)");
// 方式2:手动跳过帧
auto trace = std::stacktrace::current(1); // 跳过当前函数
std::cout << "跳过1帧:" << std::endl;
std::cout << trace << std::endl;
// 方式3:限制帧数
auto limited = std::stacktrace::current(0, 3); // 最多3帧
std::cout << "最多3帧:" << std::endl;
std::cout << limited << std::endl;
}
// ============================
// 示例4:转为字符串
// ============================
void to_string_demo() {
auto trace = std::stacktrace::current();
// 完整调用栈转字符串
std::string full = std::to_string(trace);
std::cout << "字符串形式:" << std::endl;
std::cout << full << std::endl;
// 单帧转字符串
if (!trace.empty()) {
std::string frame = std::to_string(trace[0]);
std::cout << "第一帧: " << frame << std::endl;
}
}
// ============================
// 示例5:异常中携带调用栈
// ============================
class traced_exception : public std::runtime_error {
std::stacktrace trace_;
public:
traced_exception(const std::string& msg)
: std::runtime_error(msg)
, trace_(std::stacktrace::current(1)) // 跳过构造函数本身
{}
const std::stacktrace& trace() const { return trace_; }
};
void risky_operation() {
throw traced_exception("操作失败");
}
void caller_of_risky() {
risky_operation();
}
void exception_demo() {
try {
caller_of_risky();
} catch (const traced_exception& e) {
std::cout << "异常: " << e.what() << std::endl;
std::cout << "调用栈:" << std::endl;
std::cout << e.trace() << std::endl;
}
}
// ============================
// 示例6:用迭代器遍历
// ============================
void iterator_demo() {
auto trace = std::stacktrace::current();
// 范围 for 循环
std::cout << "迭代器遍历:" << std::endl;
for (const auto& entry : trace) {
if (entry) { // 检查帧是否有效
std::cout << " " << entry.description() << std::endl;
}
}
}
// ============================
// 示例7:assert 带调用栈
// ============================
void assert_with_trace(bool condition, const std::string& msg,
std::stacktrace trace = std::stacktrace::current()) {
if (!condition) {
std::cout << "断言失败: " << msg << std::endl;
std::cout << "调用栈:" << std::endl;
for (const auto& entry : trace) {
std::cout << " " << entry.description()
<< " (" << entry.source_file()
<< ":" << entry.source_line() << ")"
<< std::endl;
}
}
}
void deeply_nested() {
int value = -1;
assert_with_trace(value >= 0, "value 应该非负");
}
void assert_demo() {
deeply_nested();
}
int main() {
std::cout << "=== 打印调用栈 ===" << std::endl;
stack_demo();
std::cout << "\n=== 逐帧访问 ===" << std::endl;
frame_access_demo();
std::cout << "\n=== 跳过帧 ===" << std::endl;
skip_demo();
std::cout << "\n=== 转字符串 ===" << std::endl;
to_string_demo();
std::cout << "\n=== 异常调用栈 ===" << std::endl;
exception_demo();
std::cout << "\n=== 迭代器 ===" << std::endl;
iterator_demo();
std::cout << "\n=== 带栈的断言 ===" << std::endl;
assert_demo();
return 0;
}stacktrace vs source_location
| 特性 | std::stacktrace | std::source_location |
|---|---|---|
| 信息范围 | 完整调用栈 | 单个调用点 |
| 运行时开销 | 有(捕获栈帧) | 无(编译期) |
| 标准版本 | C++23 | C++20 |
| 典型用途 | 错误诊断、崩溃报告 | 日志、断言 |
| 获取时机 | 运行时 | 编译期 |
适用场景
- 错误诊断和崩溃报告
- 异常中携带调用栈信息
- 调试日志中记录完整调用路径
- 性能分析工具中记录调用链
- 替代平台特定的 backtrace API
常见问题
std::stacktrace::current() 和默认构造有什么区别?
current() 捕获当前的调用栈,默认构造创建一个空的 stacktrace 对象。不要混淆。
调用栈的信息完整性取决于什么?
取决于编译选项。Release 编译可能缺少符号信息,导致函数名和行号不可用。建议在 Debug 编译或带调试符号的编译中使用。
捕获调用栈有性能开销吗?
有。捕获调用栈需要遍历栈帧,涉及符号解析。不适合在高频热路径中使用。
GCC 编译需要什么额外选项?
GCC 需要链接 -lstdc++_libbacktrace。MSVC 不需要额外选项。
编译器支持
| 编译器 | 支持 | 备注 |
|---|---|---|
| GCC | 12.1+ | 需要 -lstdc++_libbacktrace |
| MSVC | VS 2022 17.4+ | 直接支持 |
| Clang | 部分支持 | libc++ 支持进展中 |
注意事项
- 用
current()而不是默认构造来捕获栈 - 捕获调用栈有运行时开销,不要在热路径中使用
- 栈帧信息的完整性取决于编译选项和调试符号
- GCC 需要链接额外的库
- stacktrace 对象是不可变的(捕获后不能修改)
- 用作默认参数可以在调用者处捕获
总结
std::stacktrace 是 C++23 引入的标准调用栈捕获工具,提供了跨平台的运行时调用栈信息获取能力。通过 std::stacktrace::current() 捕获当前调用栈,可以逐帧访问函数名、源文件和行号。它适合用于错误诊断、异常信息增强、调试日志等场景。与 std::source_location 不同,stacktrace 获取的是完整的调用链而不是单个调用点,但有运行时开销。在异常类中嵌入 stacktrace 是一个常见的实践模式,可以在捕获异常时看到完整的调用路径。