std::source_location ​

什么是 std::source_location ​

std::source_location 是 C++20 引入的类,定义在 <source_location> 头文件中。它提供了一种无需宏即可获取源代码位置信息的方式,包括文件名、行号、列号和函数名。

在 C++20 之前,获取源代码位置需要使用 __FILE__、__LINE__、__func__ 等预处理器宏。这些宏的问题在于:它们展开在宏定义处而不是调用处,需要额外的宏包装才能正确传递。std::source_location 通过默认参数的特殊语义解决了这个问题。

cpp
#include <source_location>

void log(const std::string& msg,
         const std::source_location& loc = std::source_location::current()) {
    // loc 自动获取调用者的位置信息
}

source_location 的成员 ​

成员说明
current()静态 consteval 函数,返回调用点的位置信息
line()行号
column()列号
file_name()文件名
function_name()函数名(含签名)

基本示例 ​

cpp
#include <iostream>
#include <source_location>
#include <string>
#include <string_view>
#include <vector>
#include <format>
#include <chrono>

// ============================
// 示例1:基本用法
// ============================

void basic_demo() {
    auto loc = std::source_location::current();

    std::cout << "文件: " << loc.file_name() << std::endl;
    std::cout << "行号: " << loc.line() << std::endl;
    std::cout << "列号: " << loc.column() << std::endl;
    std::cout << "函数: " << loc.function_name() << std::endl;
}

// ============================
// 示例2:日志函数——自动获取调用者信息
// ============================

void log(std::string_view message,
         const std::source_location& loc = std::source_location::current()) {
    std::cout << "[" << loc.file_name()
              << ":" << loc.line()
              << " " << loc.function_name()
              << "] " << message << std::endl;
}

void some_function() {
    log("进入函数");         // 自动记录 some_function 的位置
    log("执行中间步骤");
    log("函数结束");
}

void log_demo() {
    log("主函数开始");       // 自动记录 log_demo 的位置
    some_function();
    log("主函数结束");
}

// ============================
// 示例3:Assert 函数(替代宏)
// ============================

void assert_check(bool condition, std::string_view msg,
                  const std::source_location& loc = std::source_location::current()) {
    if (!condition) {
        std::cout << "断言失败: " << msg << std::endl;
        std::cout << "  位置: " << loc.function_name()
                  << " (" << loc.file_name()
                  << ":" << loc.line() << ")" << std::endl;
    }
}

void assert_demo() {
    int x = 5;
    assert_check(x > 0, "x 应该大于 0");      // 通过
    assert_check(x > 10, "x 应该大于 10");     // 失败,打印位置
}

// ============================
// 示例4:对比宏方式
// ============================

// 旧方式:需要宏
#define LOG_MACRO(msg) \
    std::cout << "[" << __FILE__ << ":" << __LINE__ \
              << " " << __func__ << "] " << msg << std::endl

// 新方式:纯 C++ 函数
void log_modern(std::string_view msg,
                const std::source_location& loc = std::source_location::current()) {
    std::cout << "[" << loc.file_name() << ":" << loc.line()
              << " " << loc.function_name() << "] " << msg << std::endl;
}

void comparison_demo() {
    LOG_MACRO("旧方式");     // 宏展开
    log_modern("新方式");    // 纯函数调用
}

// ============================
// 示例5:带日志级别的日志系统
// ============================

enum class LogLevel { Debug, Info, Warning, Error };

void log_with_level(LogLevel level, std::string_view msg,
                    const std::source_location& loc = std::source_location::current()) {
    const char* level_str = "";
    switch (level) {
        case LogLevel::Debug:   level_str = "DEBUG"; break;
        case LogLevel::Info:    level_str = "INFO"; break;
        case LogLevel::Warning: level_str = "WARN"; break;
        case LogLevel::Error:   level_str = "ERROR"; break;
    }

    std::cout << "[" << level_str << "] "
              << loc.file_name() << ":" << loc.line()
              << " (" << loc.function_name() << ") "
              << msg << std::endl;
}

void level_log_demo() {
    log_with_level(LogLevel::Info, "程序启动");
    log_with_level(LogLevel::Debug, "加载配置");
    log_with_level(LogLevel::Warning, "配置项缺失,使用默认值");
    log_with_level(LogLevel::Error, "连接失败");
}

// ============================
// 示例6:记录函数调用链
// ============================

struct CallRecord {
    std::string function;
    unsigned int line;
    std::string file;
};

std::vector<CallRecord> call_stack;

void trace(const std::source_location& loc = std::source_location::current()) {
    call_stack.push_back({
        loc.function_name(),
        loc.line(),
        loc.file_name()
    });
}

void func_c() { trace(); }
void func_b() { trace(); func_c(); }
void func_a() { trace(); func_b(); }

void call_chain_demo() {
    call_stack.clear();
    func_a();

    std::cout << "调用链:" << std::endl;
    for (size_t i = 0; i < call_stack.size(); i++) {
        std::cout << "  " << i << ": " << call_stack[i].function
                  << " (行 " << call_stack[i].line << ")" << std::endl;
    }
}

// ============================
// 示例7:构造函数中使用
// ============================

class TrackedObject {
public:
    TrackedObject(const std::source_location& loc = std::source_location::current()) {
        std::cout << "  对象创建于 " << loc.function_name()
                  << " (行 " << loc.line() << ")" << std::endl;
    }
};

void constructor_demo() {
    TrackedObject a;        // 记录这行的位置
    TrackedObject b;        // 记录这行的位置

    auto make = []() {
        return TrackedObject();  // 记录 lambda 内的位置
    };
    auto c = make();
}

// ============================
// 示例8:模板函数中使用
// ============================

template<typename T>
T checked_divide(T a, T b,
                 const std::source_location& loc = std::source_location::current()) {
    if (b == T{}) {
        std::cout << "除零错误! 调用位置: "
                  << loc.function_name() << " 行 " << loc.line() << std::endl;
        return T{};
    }
    return a / b;
}

void template_demo() {
    auto r1 = checked_divide(10, 3);      // 正常
    std::cout << "10 / 3 = " << r1 << std::endl;

    auto r2 = checked_divide(10, 0);      // 除零,打印调用位置
    auto r3 = checked_divide(5.0, 0.0);   // 浮点除零
}

int main() {
    std::cout << "=== 基本用法 ===" << std::endl;
    basic_demo();

    std::cout << "\n=== 日志函数 ===" << std::endl;
    log_demo();

    std::cout << "\n=== Assert ===" << std::endl;
    assert_demo();

    std::cout << "\n=== 对比宏 ===" << std::endl;
    comparison_demo();

    std::cout << "\n=== 日志级别 ===" << std::endl;
    level_log_demo();

    std::cout << "\n=== 调用链 ===" << std::endl;
    call_chain_demo();

    std::cout << "\n=== 构造函数 ===" << std::endl;
    constructor_demo();

    std::cout << "\n=== 模板 ===" << std::endl;
    template_demo();

    return 0;
}

source_location vs 预处理器宏 ​

特性std::source_locationFILE / LINE
类型安全是(C++ 对象)否(宏展开)
可作为参数传递是(默认参数)需要宏包装
调试器友好是否
编译期可用是(consteval)是
获取函数签名是(含模板参数)func 只有名称
可用于模板是是

适用场景 ​

  • 日志系统中自动记录调用位置
  • 自定义 assert 函数
  • 错误报告和异常消息
  • 调试工具和追踪系统
  • 替代 FILE、LINE、func 宏

常见问题 ​

current() 为什么用作默认参数?

current() 是 consteval 的,当用作默认参数时,它在调用者的上下文中求值,因此能获取调用者的位置信息。如果在函数体内调用 current(),获取的是当前函数的位置。

source_location 对象的大小是多少?

取决于实现。GCC 和 Clang 的实现通常是两个指针 + 两个整数(约 24 字节,64位平台)。MSVC 可能更大。建议通过 const & 传递。

可以在 constexpr 上下文中使用吗?

current() 是 consteval 的,line()、column()、file_name()、function_name() 都是 constexpr 的。

function_name 返回的格式是什么?

由实现定义。GCC 返回类似 void foo(int) 的格式,MSVC 可能返回 void __cdecl foo(int)。不同编译器的格式不同。

注意事项 ​

  • current() 必须用作默认参数才能获取调用者的位置
  • function_name() 的格式是实现定义的
  • 建议通过 const 引用传递 source_location 对象
  • source_location 参数应该放在参数列表的最后
  • 需要 <source_location> 头文件

总结 ​

std::source_location 是 C++20 提供的源代码位置信息工具,替代了 __FILE__、__LINE__、__func__ 等宏。它的核心用法是作为函数的默认参数——current() 在调用者的上下文中求值,自动获取调用者的文件名、行号和函数名。这让日志函数、assert 函数、错误报告等不再需要宏包装,代码更类型安全、更容易调试。它是构建现代 C++ 日志和诊断系统的基础工具。