c++20 source_location 追踪代码执行路径

std::source_location 是 C++20 中引入的一个工具类,旨在以类型安全且灵活的方式捕获源代码的位置信息(如文件名、行号、函数名等),替代传统的预处理器宏(如 __LINE____FILE__,__fun__)。

核心特性

  1. 用途
    用于在编译时获取代码位置信息,常用于日志记录、调试、断言等场景,能更准确地追踪代码执行路径。

  2. 成员函数

    • line(): 返回当前代码的行号。
    • column(): 返回当前代码的列号。
    • file_name(): 返回当前源文件的名称。
    • function_name(): 返回当前函数的名称。
  3. 静态方法

    • current(): 返回表示调用点位置的 source_location 对象,通常在函数参数中调用以捕获调用者位置。
  4. 其他特性

    • 字面类型(LiteralType),支持编译时构造。
    • 所有成员函数为 constexpr,允许在编译时获取信息。
    • 无法手动构造实例,只能通过 current() 获取。

使用场景代码示例:

1、日志记录源码位置

#include 
#include 
#include 

using namespace std;

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

void work() {
	log("begin");
}

int main() {
	work();
}

这里有一个小技巧,log函数的第二个参数source_location静态方法current()的结果作为默认值参数,对current的调用是在 log("begin") 这一行。所以能正确显示我们感兴趣的位置。

2、定位异常的源码位置

#include 
#include 
#include 
#include 

using namespace std;

class LocateException : public exception {
public:
	LocateException(string message, source_location sl = source_location::current()):
		message_{move(message)}, location_{move(sl)}{}
	const char* what() const noexcept override { return message_.c_str(); }
	virtual const source_location& where() const noexcept { return location_; }
private:
	string message_;
	source_location location_;
};

void work() {
	throw LocateException{ "test exception" };
}

int main() {
	try {
		work();
	}
	catch(const LocateException& e){
		const auto& location{ e.where() };
		cerr << format("caught exception {} in file {}, at line {}", e.what(), location.file_name(), location.line()) << endl;
	}
}

你可能感兴趣的:(c++20)