目录
1. Include and Capture Source Location Automatically
2. Use in Macros for Cleaner Logging
3. Customize Log Format and Add Extra Context
4. Optimize for Performance
5. Capture Column and Other Details (Rarely Used)
Summary
首页 后端开发 C++ 如何使用C 20的STD :: source_location以获得更好的记录?

如何使用C 20的STD :: source_location以获得更好的记录?

Aug 11, 2025 pm 08:55 PM

使用std::source_location::current() 作为默认参数可自动捕获调用点的文件名、行号和函数名;2. 可通过宏如#define LOG(msg) log(msg, std::source_location::current()) 简化日志调用;3. 可结合日志级别、时间戳等信息扩展日志内容;4. 为优化性能,可省略函数名或在发布版本中禁用位置信息;5. column() 等细节较少使用,但可用。使用std::source_location 能以极低开销显着提升日志的调试价值,无需手动传入FILE 或__LINE__,让编译器自动完成上下文捕获,从而实现更高效、清晰的诊断输出。

How to use std::source_location from C  20 for better logging?

std::source_location in C 20 is a lightweight utility that captures information about the source code's context—like file name, line number, function name, and column—at the point where it's used. It's incredibly useful for improving logging by automatically including diagnostic context without requiring manual input.

How to use std::source_location from C  20 for better logging?

Here's how to use std::source_location effectively for better logging.


1. Include and Capture Source Location Automatically

std::source_location is defined in the <source_location></source_location> header (C 20). It's a constexpr -friendly class that captures location info at the call site when used with default arguments.

How to use std::source_location from C  20 for better logging?
 #include <iostream>
#include <string_view>
#include <source_location>

void log(std::string_view message,
         std::source_location location = std::source_location::current())
{
    std::cout << location.file_name() << ":"
              << location.line() << " "
              << location.function_name() << "() - "
              << message << &#39;\n&#39;;
}

Now when you call log("Something happened"); , the file, line, and function are captured automatically.

Example usage:

How to use std::source_location from C  20 for better logging?
 void my_function() {
    log("Debug message"); // Automatically prints file, line, function
}

Output might look like:

 main.cpp:15 my_function() - Debug message

2. Use in Macros for Cleaner Logging

To avoid passing source_location manually every time, wrap the logging in a macro—though with C 20, you often don't need macros thanks to default parameter capture.

But if you want a clean interface (eg, LOG("msg") ), a macro helps:

 #define LOG(msg) log(msg, std::source_location::current())

// Usage
LOG("Error occurred");

This ensures the location is captured at the macro call site, not inside the log function.

Note: Since std::source_location::current() is a built-in compiler intrinsic, the macro isn't strictly necessary, but it makes the syntax cleaner and more familiar.


3. Customize Log Format and Add Extra Context

You can extend the logger to include timestamps, log levels, or custom tags.

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

void log(LogLevel level, std::string_view message,
         std::source_location loc = std::source_location::current())
{
    const char* level_str[] = {"DEBUG", "INFO", "WARNING", "ERROR"};

    std::cout << "[" << level_str[static_cast<int>(level)] << "] "
              << loc.file_name() << ":" << loc.line() << " "
              << loc.function_name() << " - "
              << message << &#39;\n&#39;;
}

Usage:

 log(LogLevel::Warning, "Value out of range");

Output:

 [WARNING] config.cpp:42 parse_config() - Value out of range

4. Optimize for Performance

std::source_location is lightweight, but capturing function names (which may include full signatures and templates) can be expensive in terms of binary size or performance.

If you don't need the function name, skip it:

 std::cout << loc.file_name() << ":" << loc.line();

Or, use conditional compilation to disable location info in release builds:

 #ifdef DEBUG
    auto loc = std::source_location::current();
    std::cout << loc.file_name() << ":" << loc.line() << " ";
#else
    std::cout << "[debug info disabled] ";
#endif

Alternatively, design your logging system so that debug-level logs (with full location) are compiled out when not needed.


5. Capture Column and Other Details (Rarely Used)

std::source_location also provides column() and file_name() / function_name() as const char* . Column is rarely useful but available.

 std::cout << "Column: " << loc.column() << &#39;\n&#39;; // Usually 1 or not very meaningful

Most compilers set column to the start of the statement, so it's not commonly used.


Summary

  • Use std::source_location::current() as a default function parameter to auto-capture location.
  • Avoid macros if you're okay with plain function calls; otherwise, use them for cleaner syntax.
  • Include file, line, and function in logs to speed up debugging.
  • Be mindful of performance and binary bloat from long function names.
  • Combine with log levels and formatting for production-ready logging.

Using std::source_location makes logging more informative with almost zero effort—no more manually writing __FILE__ or __LINE__ . It's a small feature with a big impact on debuggability.

Basically, just add it to your logging function and let the compiler do the rest.

以上是如何使用C 20的STD :: source_location以获得更好的记录?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Laravel 教程
1604
29
PHP教程
1510
276
C初始化技术 C初始化技术 Jul 18, 2025 am 04:13 AM

C 中有多种初始化方式,适用于不同场景。1.基本变量初始化包括赋值初始化(inta=5;)、构造初始化(inta(5);)和列表初始化(inta{5};),其中列表初始化更严格且推荐使用;2.类成员初始化可通过构造函数体赋值或成员初始化列表(MyClass(intval):x(val){}),后者更高效并适用于const和引用成员,C 11还支持类内直接初始化;3.数组和容器初始化可使用传统方式或C 11的std::array和std::vector,支持列表初始化并提升安全性;4.默认初

对象切片 对象切片 Jul 17, 2025 am 02:19 AM

对象切片是指将派生类对象赋值或传递给基类对象时,仅复制基类部分数据,导致派生类新增成员丢失的现象。1.对象切片发生在直接赋值、按值传参或多态对象存入存储基类的容器中;2.其后果包括数据丢失、行为异常及难以调试的问题;3.避免方法包括使用指针或引用传递多态对象,或使用智能指针管理对象生命周期。

在C中使用STD ::可选 在C中使用STD ::可选 Jul 21, 2025 am 01:52 AM

要判断std::optional是否有值,可使用has_value()方法或直接在if语句中判断;返回可能为空的结果时推荐使用std::optional,避免空指针和异常;不应滥用,某些场景下布尔返回值或独立bool变量更合适;初始化方式多样,但需注意使用reset()清空值,并留意生命周期和构造行为。

在C中解释RAII 在C中解释RAII Jul 22, 2025 am 03:27 AM

RAII是C 中用于资源管理的重要技术,其核心在于通过对象生命周期自动管理资源。它的核心思想是:资源在构造时获取,在析构时释放,从而避免手动释放导致的泄漏问题。例如,在没有RAII时,文件操作需手动调用fclose,若中途出错或提前return就可能忘记关闭文件;而使用RAII后,如FileHandle类封装文件操作,离开作用域后会自动调用析构函数释放资源。1.RAII应用于锁管理(如std::lock_guard)、2.内存管理(如std::unique_ptr)、3.数据库和网络连接管理等

c向量获得第一个元素 c向量获得第一个元素 Jul 25, 2025 am 12:35 AM

获取std::vector的第一个元素有四种常用方法:1.使用front()方法,需确保vector非空,语义清晰且推荐日常使用;2.使用下标[0],同样需判空,性能与front()相当但语义稍弱;3.使用*begin(),适用于泛型编程和STL算法配合;4.使用at(0),无需手动判空但性能较低,越界时抛出异常,适合调试或需要异常处理的场景;最佳实践是先调用empty()检查是否为空,再使用front()方法获取第一个元素,避免未定义行为。

了解c中的移动分配运算符 了解c中的移动分配运算符 Jul 16, 2025 am 02:20 AM

theSoveassignmentOperatorINC ISASPECIALFUNCTERTHATEFFELYTRANSFERSFERSOURCERCOMPORAMEBARPARYOBJEMTTOTOANEXISTINE.ISDEFIENDIENASMYCLASS&operator =(myclass && other)noexcept; takeanon-constanon-constranon-constranon-constravalueReReReReReReereFerenceToallenCalloFerencalloAllAlawalLencefiencifienaofthesifificeofthesourtheSour

什么是C中的破坏者? 什么是C中的破坏者? Jul 19, 2025 am 03:15 AM

C 中的析构函数是一种特殊的成员函数,会在对象离开作用域或被显式删除时自动调用。它的主要作用是清理对象在其生命周期内可能获取的资源,如内存、文件句柄或网络连接。析构函数在以下情况下自动调用:局部变量离开作用域时、对指针调用delete时、包含对象的外部对象析构时。定义析构函数时需在类名前加~,且无参数和返回值。若未定义,编译器会生成默认析构函数,但不会处理动态内存释放。注意事项包括:每个类只能有一个析构函数,不支持重载;建议将继承类的析构函数设为virtual;派生类析构函数先执行,再自动调用

C标准库解释 C标准库解释 Jul 25, 2025 am 02:11 AM

C 标准库通过提供高效工具帮助开发者提升代码质量。 1.STL容器应根据场景选择,如vector适合连续存储,list适合频繁插入删除,unordered_map适合快速查找;2.标准库算法如sort、find、transform能提高效率并减少错误;3.智能指针unique_ptr和shared_ptr有效管理内存,避免泄漏;4.其他工具如optional、variant、function增强代码安全性与表达力。掌握这些核心功能可显着优化开发效率与代码质量。

See all articles