std::format 与 printf 安全性对比 ​

面试考点 ​

C++20 的 std::format 是 printf 的现代替代品。面试官通过这道题考察你是否理解两者在类型安全、编译期检查、可扩展性上的根本差异,以及 std::format 如何消除 printf 的常见安全漏洞。

核心概念 ​

printf 使用 % 格式说明符,依赖程序员手动匹配类型,类型不匹配是未定义行为。std::format 使用 {} 占位符,编译器在编译期检查格式字符串和参数类型是否匹配,类型不匹配是编译错误。

基本示例 ​

cpp
#include <iostream>
#include <format>
#include <string>
#include <vector>
#include <cstdio>
#include <chrono>

// ============================
// 示例1:类型安全对比
// ============================

void type_safety_demo() {
    int n = 42;
    double pi = 3.14159;
    const char* name = "Alice";

    // printf:程序员负责类型匹配
    printf("name=%s, n=%d, pi=%f\n", name, n, pi);  // 正确

    // printf 类型不匹配:未定义行为!
    // printf("n=%s\n", n);     // %s 期望 const char*,传了 int
    // printf("pi=%d\n", pi);   // %d 期望 int,传了 double
    // 编译器可能给警告,但不是错误

    // std::format:编译器检查类型
    std::string s1 = std::format("name={}, n={}, pi={}", name, n, pi);
    std::cout << s1 << std::endl;

    // std::format 类型不匹配:编译错误!
    // std::string s2 = std::format("{:d}", "not a number");
    // 编译期就报错,不会到运行时
}

// ============================
// 示例2:缓冲区溢出安全
// ============================

void buffer_safety_demo() {
    char buf[10];

    // sprintf:没有边界检查,缓冲区溢出!
    // sprintf(buf, "%s", "this is a very long string");  // 溢出!未定义行为

    // snprintf:有长度限制,但截断时可能丢失数据
    snprintf(buf, sizeof(buf), "%s", "this is a very long string");
    printf("snprintf: %s\n", buf);  // 截断为 "this is a"

    // std::format:返回 std::string,自动管理内存,不可能溢出
    std::string result = std::format("{}", "this is a very long string");
    std::cout << "format: " << result << std::endl;  // 完整字符串

    // std::format_to:输出到迭代器,也不会溢出
    std::string output;
    std::format_to(std::back_inserter(output), "x={}, y={}", 1, 2);
    std::cout << "format_to: " << output << std::endl;
}

// ============================
// 示例3:参数数量安全
// ============================

void arg_count_demo() {
    // printf:参数多了或少了都是未定义行为
    // printf("%d %d\n", 1);        // 少了一个参数,未定义行为
    // printf("%d\n", 1, 2, 3);    // 多了参数,被忽略(不报错)

    // std::format:参数数量必须匹配
    // std::string s = std::format("{} {}", 1);  // 编译错误:参数不够
    // 多余的参数也会报错

    // 正确用法
    std::string s = std::format("{} {}", 1, 2);
    std::cout << s << std::endl;
}

// ============================
// 示例4:位置参数
// ============================

void positional_demo() {
    // printf 的位置参数(非标准扩展,可移植性差)
    // printf("%2$s is %1$d years old\n", 25, "Alice");

    // std::format:标准支持位置参数
    std::string s1 = std::format("{1} is {0} years old", 25, "Alice");
    std::cout << s1 << std::endl;  // "Alice is 25 years old"

    // 可以重复使用参数
    std::string s2 = std::format("{0}{0}{0}", "ha");
    std::cout << s2 << std::endl;  // "hahaha"
}

// ============================
// 示例5:自定义类型格式化
// ============================

struct Point {
    double x, y;
};

// printf 无法直接格式化自定义类型
// 必须手动拆分成基本类型

// std::format 可以通过特化 std::formatter 支持自定义类型
template<>
struct std::formatter<Point> {
    constexpr auto parse(std::format_parse_context& ctx) {
        return ctx.begin();  // 不解析额外的格式说明
    }

    auto format(const Point& p, std::format_context& ctx) const {
        return std::format_to(ctx.out(), "({}, {})", p.x, p.y);
    }
};

void custom_type_demo() {
    Point p{1.5, 2.5};

    // printf:需要手动拆分
    printf("Point: (%f, %f)\n", p.x, p.y);

    // std::format:直接格式化
    std::cout << std::format("Point: {}", p) << std::endl;
}

// ============================
// 示例6:格式说明符对比
// ============================

void format_spec_demo() {
    int n = 42;

    // printf 格式说明符
    printf("十进制: %d\n", n);
    printf("十六进制: %x\n", n);
    printf("八进制: %o\n", n);
    printf("宽度填充: %010d\n", n);
    printf("左对齐: %-10d|\n", n);

    // std::format 格式说明符
    std::cout << std::format("十进制: {}\n", n);
    std::cout << std::format("十六进制: {:x}\n", n);
    std::cout << std::format("八进制: {:o}\n", n);
    std::cout << std::format("宽度填充: {:010}\n", n);
    std::cout << std::format("左对齐: {:<10}|\n", n);
    std::cout << std::format("居中: {:^10}|\n", n);

    // std::format 独有:自定义填充字符
    std::cout << std::format("填充: {:*>10}\n", n);   // ********42
    std::cout << std::format("填充: {:*^10}\n", n);   // ****42****
}

// ============================
// 示例7:C++23 的 std::print
// ============================

/*
C++23 引入 std::print,结合了 std::format 的安全性和直接输出:

    std::print("Hello, {}!\n", "World");
    // 等价于 std::cout << std::format("Hello, {}!\n", "World");
    // 但更高效(避免了构造临时 string)

    std::println("x={}, y={}", 1, 2);
    // 自动添加换行符

std::print 是 printf 的真正现代替代品:
- 类型安全(编译期检查)
- 直接输出(不构造中间 string)
- 支持自定义类型
*/

int main() {
    std::cout << "=== 类型安全 ===" << std::endl;
    type_safety_demo();

    std::cout << "\n=== 缓冲区安全 ===" << std::endl;
    buffer_safety_demo();

    std::cout << "\n=== 参数数量 ===" << std::endl;
    arg_count_demo();

    std::cout << "\n=== 位置参数 ===" << std::endl;
    positional_demo();

    std::cout << "\n=== 自定义类型 ===" << std::endl;
    custom_type_demo();

    std::cout << "\n=== 格式说明符 ===" << std::endl;
    format_spec_demo();

    return 0;
}

printf vs std::format 全面对比 ​

维度printfstd::format
类型安全无(依赖程序员匹配 %d, %s)编译期检查类型
格式说明符%d, %s, %f, %x 等{}, {:d}, {:x} 等
缓冲区安全sprintf 可溢出返回 string,不会溢出
参数数量检查不检查编译期检查
自定义类型不支持特化 std::formatter
位置参数非标准扩展标准支持 {0},
性能快(直接输出)略慢(构造 string)或相当
编译期检查编译器警告(非必须)编译错误(强制)
国际化差好(支持参数重排)
C 兼容完全兼容不兼容 C

printf 的安全漏洞 ​

漏洞类型例子后果
类型不匹配printf("%s", 42)未定义行为,可能崩溃
缓冲区溢出sprintf(buf, "%s", long_str)内存覆写,安全漏洞
参数不足printf("%d %d", 1)读取栈上的垃圾值
格式字符串攻击printf(user_input)信息泄露或代码执行
%n 写入printf("%n", &count)任意内存写入

常见问题 ​

std::format 比 printf 慢吗?

在大多数场景下性能相当。std::format 返回 std::string 需要堆分配,这是主要开销。但 std::format_to 可以避免这个分配,直接输出到缓冲区。C++23 的 std::print 直接输出到文件流,性能和 printf 相当甚至更快(因为可以利用类型信息优化)。

为什么 std::format 能做编译期检查?

格式字符串在 C++20 中通过 consteval 构造函数在编译期解析。编译器在编译时知道格式字符串的内容和参数的类型,可以验证两者是否匹配。如果不匹配,直接产生编译错误而不是运行时异常。

什么时候还需要用 printf?

三种情况:1) 必须和 C 代码互操作;2) 编译器不支持 C++20;3) 极端性能敏感的热路径,且测量证明 printf 更快。新 C++ 代码应该优先使用 std::format 或 C++23 的 std::print。

适用场景 ​

  • 任何需要字符串格式化的场景(std::format)
  • 日志输出(std::format 或 std::print)
  • 用户界面文本(支持位置参数利于国际化)
  • 调试输出(类型安全避免格式错误)

注意事项 ​

  • std::format 的格式字符串必须是编译期常量(字面量)
  • 运行时格式字符串需要用 std::vformat(失去编译期检查)
  • std::format 不导出 C 的宏或全局函数
  • 自定义 formatter 的 parse 函数必须是 constexpr
  • C++23 的 std::print 是最推荐的输出方式

总结 ​

std::format 从根本上解决了 printf 的安全问题:编译期类型检查消除了类型不匹配,返回 string 消除了缓冲区溢出,编译期参数数量检查消除了参数遗漏。面试中要能列举 printf 的安全漏洞(类型不匹配、缓冲区溢出、格式字符串攻击),解释 std::format 如何用编译期检查解决这些问题,以及知道 C++23 std::print 作为直接输出的方案。