调试与诊断

写代码必然会有 bug。现代 C++ 开发的核心理念之一是:尽早发现问题——能在编译期发现就不要拖到运行时,能在开发阶段发现就不要等到部署之后。本章介绍一整套从编译期到运行时的诊断工具链,帮助你在第一时间定位并修复问题。

编译器警告是你的朋友

编译器会检测到许多常见的编程错误和可疑模式,但默认只报告一小部分。在项目开始的第一天,就应该开启尽可能多的警告,并将警告视为错误。

GCC / Clang 推荐选项

# 开发阶段的推荐编译选项
g++ -std=c++23 -Wall -Wextra -Wpedantic -Werror main.cpp -o main

# 各选项含义:
# -Wall        启用大多数常见警告
# -Wextra      额外警告(未使用参数、符号比较混合等)
# -Wpedantic   严格遵循 ISO C++ 标准
# -Werror      将所有警告视为错误(编译不通过)

MSVC 推荐选项

# MSVC (Visual Studio / cl.exe)
cl /std:c++latest /W4 /WX main.cpp

# /W4   最高实用警告级别(/Wall 会包含大量库内部警告,通常过多)
# /WX   将警告视为错误

警告能帮你抓 bug 的真实例子

#include <print>

int calculate_discount(int price, int quantity) {
    int discount;          // 未初始化!
    if (quantity > 100) {
        discount = 20;
    }
    // 当 quantity  100) {
        discount = 20;
    }
    return price * discount / 100;
}

实践建议:在 CMakeLists.txt 中统一设置警告选项,确保团队每位成员都使用相同的编译标准:

if(MSVC)
    target_compile_options(myapp PRIVATE /W4 /WX)
else()
    target_compile_options(myapp PRIVATE -Wall -Wextra -Wpedantic -Werror)
endif()

还有一些更有针对性的警告值得开启:

# 更多有用的 GCC/Clang 警告
-Wconversion        # 隐式类型转换(如 double → int)
-Wshadow            # 变量名遮蔽外层作用域
-Wnon-virtual-dtor  # 有虚函数但析构函数不是 virtual
-Wold-style-cast    # C 风格强制转换
-Wformat=2          # printf 格式字符串检查

Sanitizers (运行时检测工具)

编译器警告只能发现静态可分析的问题。还有一类 bug 只在特定运行路径下才会触发——这正是 Sanitizer 的用武之地。Sanitizer 在编译时给程序注入额外检测代码,运行时如果检测到违规操作,会立即报告并终止程序。

Address Sanitizer (ASan)

检测各种内存访问错误:

// 示例:ASan 能捕获的三类典型错误

// 1. 栈缓冲区溢出
void buffer_overflow() {
    int arr[5] = {1, 2, 3, 4, 5};
    int val = arr[10];   // [错误] ASan: stack-buffer-overflow
    std::println("{}", val);
}

// 2. 使用已释放的内存
void use_after_free() {
    int* p = new int{42};
    delete p;
    *p = 100;            // [错误] ASan: heap-use-after-free
}

// 3. 返回局部变量的地址
int* dangling_pointer() {
    int local = 42;
    return &local;       // [错误] ASan: stack-use-after-return
}

Undefined Behavior Sanitizer (UBSan)

检测 C++ 标准中定义为"未定义行为"的操作。这些代码可能"看起来能正常运行",但实际上不可移植、不可靠:

// 示例:UBSan 能捕获的未定义行为

#include <climits>
#include <print>

// 1. 有符号整数溢出
int overflow_example() {
    int x = INT_MAX;
    return x + 1;       // [错误] UBSan: signed integer overflow
    // 注意:无符号整数溢出是定义好的(取模),不算 UB
}

// 2. 空指针解引用
void null_deref(int* p) {
    std::println("{}", *p);  // [错误] 如果 p == nullptr: UBSan 报错
}

// 3. 除以零
int divide(int a, int b) {
    return a / b;        // [错误] 如果 b == 0: UBSan 报错
}

// 4. 数组越界移位
int bad_shift(int x) {
    return x << 33;     // [错误] UBSan: shift exponent >= width of type
}

如何启用 Sanitizer

# 命令行启用(GCC/Clang)
g++ -std=c++23 -g -fsanitize=address,undefined -fno-omit-frame-pointer main.cpp -o main

# -g                       保留调试信息(报错时显示源码位置)
# -fsanitize=address       启用 ASan
# -fsanitize=undefined     启用 UBSan
# -fno-omit-frame-pointer  保留栈帧指针(让 backtrace 更准确)

在 CMake 中启用 Sanitizer

# CMakeLists.txt — 推荐通过一个选项控制
option(ENABLE_SANITIZERS "Enable ASan + UBSan" OFF)

if(ENABLE_SANITIZERS)
    target_compile_options(myapp PRIVATE
        -fsanitize=address,undefined
        -fno-omit-frame-pointer
    )
    target_link_options(myapp PRIVATE
        -fsanitize=address,undefined
    )
endif()

# 使用:cmake -B build -DENABLE_SANITIZERS=ON

注意事项:ASan 会使程序运行速度降低约 2 倍,内存占用增加约 3 倍。它适合在开发和测试阶段使用,不要在生产环境启用。另外,ASan 和 ThreadSanitizer (TSan) 不能同时启用。

一个"看起来正常"但有 UB 的完整示例

#include <print>
#include <vector>

// 这段代码在 -O0 下"可能正常",在 -O2 下可能产生诡异结果
bool is_valid_index(int index, int size) {
    // 有符号整数溢出是 UB!编译器可能优化掉这个检查
    return index + 1 > 0 && index < size;
}

int main() {
    std::vector<int> data = {10, 20, 30};

    int idx = INT_MAX;  // 极端输入
    if (is_valid_index(idx, static_cast<int>(data.size()))) {
        std::println("data[{}] = {}", idx, data[idx]);  // 灾难!
    }
}
// 用 UBSan 编译运行会立即报告:
// runtime error: signed integer overflow: 2147483647 + 1
//   cannot be represented in type 'int'

断点调试 (Breakpoint Debugging)

当 print 调试无法定位问题时,需要使用调试器来逐行执行代码、检查变量状态、观察调用栈。

GDB / LLDB 基础命令

# 编译时加 -g 保留调试信息
g++ -std=c++23 -g -O0 main.cpp -o main

# 启动 GDB
gdb ./main

# LLDB(macOS 默认)
lldb ./main
操作 GDB 命令 LLDB 命令 说明
设置断点 break main.cpp:42 b main.cpp:42 在第 42 行停下
函数断点 break calculate b calculate 进入函数时停下
运行 run run 开始执行
下一行 next / n next / n 执行当前行,不进入函数
步入 step / s step / s 进入函数内部
继续 continue / c continue / c 继续运行到下个断点
查看变量 print x p x 打印变量值
调用栈 backtrace / bt bt 显示函数调用链
条件断点 break 42 if x > 100 b 42 -c 'x > 100' 满足条件时才停下

VS Code 调试配置

在 .vscode/launch.json 中配置:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug C++",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/build/main",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "build"
        }
    ]
}

条件断点的典型场景:循环执行上万次,但 bug 只在第 9999 次出现。设置 break 42 if i == 9999,调试器会自动在条件满足时停下,省去手动跳过 9998 次的痛苦。

static_assert (编译期断言)

static_assert 在编译期检查条件是否为真。如果条件为 false,编译立即终止并输出你指定的错误信息。这是"把错误推到编译期"这一哲学的直接体现。

基础用法

// 验证平台假设
static_assert(sizeof(void*) == 8, "This code requires a 64-bit platform");
static_assert(sizeof(int) == 4, "int must be 32 bits");

// 验证类型特性
#include <type_traits>

struct Widget {
    std::string name;
    int value;
};

// 确保 Widget 支持移动语义
static_assert(std::is_move_constructible_v<Widget>,
              "Widget must be move constructible");

// 确保 Widget 不会被意外复制(如果设计为 move-only)
// static_assert(!std::is_copy_constructible_v<Handle>,
//               "Handle should be move-only");

在模板中使用 static_assert

#include <type_traits>
#include <print>

// 确保模板参数满足要求
template<typename T>
T safe_add(T a, T b) {
    static_assert(std::is_arithmetic_v<T>,
                  "safe_add only works with numeric types");
    static_assert(std::is_signed_v<T>,
                  "safe_add requires signed types for overflow detection");

    // 检测溢出(简化版)
    if (b > 0 && a > std::numeric_limits<T>::max() - b) {
        throw std::overflow_error("addition overflow");
    }
    return a + b;
}

// safe_add(1, 2);            // [正确] OK — int is signed arithmetic
// safe_add("hi", "lo");      // [错误] 编译错误: only works with numeric types
// safe_add(1u, 2u);          // [错误] 编译错误: requires signed types

C++17: 无消息的 static_assert

// C++17 起,消息参数是可选的
static_assert(sizeof(int) >= 4);    // OK,但推荐写上消息
static_assert(std::is_trivially_copyable_v<int>);  // 自说明

何时用 static_assert vs concepts:如果你在写模板接口、需要提供清晰的约束错误信息,优先使用 Concepts (卷四)。static_assert 更适合在函数/类内部验证某些不变量或平台假设。

std::source_location (C++20)

传统的 __FILE__ 和 __LINE__ 宏虽然能用,但它们是预处理器的产物,无法与现代 C++ 的类型系统很好地配合。C++20 引入了 std::source_location,用类型安全的方式获取调用位置信息。

基本 API

#include <source_location>
#include <print>

void show_location(std::source_location loc = std::source_location::current()) {
    std::println("文件: {}", loc.file_name());
    std::println("行号: {}", loc.line());
    std::println("列号: {}", loc.column());
    std::println("函数: {}", loc.function_name());
}

int main() {
    show_location();
    // 输出:
    // 文件: main.cpp
    // 行号: 12     (main 中调用 show_location 的那一行)
    // 列号: 5
    // 函数: int main()
}

构建自定义 log 函数

#include <source_location>
#include <print>
#include <string_view>

enum class LogLevel { debug, info, warn, error };

void log(std::string_view msg,
         LogLevel level = LogLevel::info,
         std::source_location loc = std::source_location::current())
{
    constexpr const char* level_str[] = {"DEBUG", "INFO", "WARN", "ERROR"};
    std::println("[{} {}:{}] {}",
                 level_str[static_cast<int>(level)],
                 loc.file_name(),
                 loc.line(),
                 msg);
}

int main() {
    log("Server started");
    // [INFO main.cpp:22] Server started

    log("Connection timeout", LogLevel::warn);
    // [WARN main.cpp:25] Connection timeout

    log("Database error", LogLevel::error);
    // [ERROR main.cpp:28] Database error
}

自定义断言宏的替代品

#include <source_location>
#include <print>
#include <cstdlib>
#include <string_view>

// 比传统 assert 宏更安全、信息更丰富的断言函数
inline void my_assert(bool condition,
                      std::string_view expr,
                      std::source_location loc = std::source_location::current())
{
    if (!condition) {
        std::println(stderr, "Assertion failed: '{}'\n  at {}:{} in {}",
                     expr, loc.file_name(), loc.line(), loc.function_name());
        std::abort();
    }
}

// 用一个简单宏传递表达式文本
#define MY_ASSERT(expr) my_assert(static_cast<bool>(expr), #expr)

void process(int* data, int size) {
    MY_ASSERT(data != nullptr);
    MY_ASSERT(size > 0);
    // ...
}
// 如果失败,输出:
// Assertion failed: 'data != nullptr'
//   at main.cpp:31 in void process(int*, int)

注意:std::source_location::current() 必须作为默认参数使用,不能在函数体内调用——否则它会捕获定义位置而非调用位置。这是一个常见的误用。

实用调试技巧

Print 调试没什么丢人的

在很多场景下,std::println 就是最快的调试手段。关键是使用后要清理掉:

#include <print>

void process_data(const std::vector<int>& data) {
    std::println("[DEBUG] data.size() = {}", data.size());

    for (int i = 0; auto& val : data) {
        if (val < 0) {
            std::println("[DEBUG] negative value at index {}: {}", i, val);
        }
        ++i;
    }
}

// 更好的做法:用条件编译控制调试输出
#ifdef NDEBUG
    #define DBG_PRINT(...) ((void)0)
#else
    #define DBG_PRINT(...) std::println(__VA_ARGS__)
#endif

使用 Compiler Explorer 检查生成代码

访问 godbolt.org,将你的代码粘贴进去,可以直接看到编译器生成的汇编代码。这对理解以下问题特别有帮助:

  • 内联是否生效
  • 优化器是否消除了不必要的拷贝
  • 编译器是否将循环向量化
  • constexpr 计算是否在编译期完成
// 在 Compiler Explorer 中对比这两个版本:

// 版本 A:按值传递 string
void process_a(std::string s) { /* ... */ }

// 版本 B:按 const 引用传递
void process_b(const std::string& s) { /* ... */ }

// 观察汇编,你会发现版本 A 多了一次拷贝构造/析构

读懂编译器错误信息

模板相关的错误信息通常很长。关键技巧:

  1. 看第一个错误——后续错误往往是连锁反应
  2. 找你的文件名——跳过标准库内部的信息
  3. 找 "required from here"——这是你的代码触发模板实例化的位置
// 典型场景:不小心传了错误类型给算法
#include <algorithm>
#include <vector>

struct Point { int x, y; };

void sort_points(std::vector<Point>& points) {
    std::sort(points.begin(), points.end());  // [错误] 编译错误!
    // 错误信息的核心:Point 没有 operator<
    // 修复:提供比较函数
    std::sort(points.begin(), points.end(),
              [](const Point& a, const Point& b) {
                  return a.x < b.x;
              });  // [正确]
}

实用工具推荐:

  • Compiler Explorer (godbolt.org) — 在线查看汇编
  • C++ Insights (cppinsights.io) — 查看编译器如何展开模板和语法糖
  • Valgrind — Linux 下的内存检测工具(比 ASan 慢但更全面)
  • clang-tidy — 静态分析,可检测数百种模式

调试检查清单

当遇到 bug 时,按以下顺序排查:

  1. 是否开启了全部警告?先用 -Wall -Wextra 编译看看
  2. 用 ASan/UBSan 重新编译运行——是内存错误还是 UB?
  3. 在 Compiler Explorer 中检查——优化器是否做了意料之外的事?
  4. 设置断点逐行检查——变量的值是否符合预期?
  5. 缩小范围——写一个最小复现用例

本章小结

  • 编译器警告:从第一天起开启 -Wall -Wextra -Wpedantic -Werror,让编译器帮你找 bug
  • Sanitizers:ASan 检测内存错误,UBSan 检测未定义行为——开发阶段必开
  • 调试器:掌握 GDB/LLDB 基本命令,善用条件断点
  • static_assert:在编译期验证假设,让错误无法逃到运行时
  • std::source_location:C++20 替代 __FILE__/__LINE__,构建类型安全的日志/断言
  • 工具链:Compiler Explorer、C++ Insights、clang-tidy 是日常开发利器