Namespaces
Variants

std::source_location::current

来自 zh.cppreference.net
 
 
 
 
static consteval source_location current() noexcept;
(since C++20)

构造一个新的 source_location对象,该对象对应于调用点的位置。

返回值

如果直接调用 current() (通过显式命名 current() 的函数调用),它将返回一个 source_location 对象,该对象包含表示调用位置的实现定义值。这些值应受到 #line 预处理器指令 的影响,其影响方式与预定义宏 __LINE__ 和 __FILE__ 相同。

如果在 默认成员初始化器 中使用 current() ,其返回值对应于初始化该数据成员的构造函数定义或 聚合初始化 的位置。

如果在默认参数中使用 current() ,其返回值对应于调用点处 current() 的调用位置。

如果以任何其他方式调用 current() ,返回值是未指定的。

注释

std::source_location::current 通常需要编译器的内置实现。

示例

#include <print>
#include <source_location>

struct src_rec
{
    std::source_location srcl = std::source_location::current();
    int dummy{};

    src_rec(std::source_location loc = std::source_location::current()) :
        srcl(loc)    // values of member refer to the location of the calling function
    {}
    src_rec(int i) : // values of member refer to this location
        dummy(i)
    {}
    src_rec(double)  // values of member refer to this location
    {}
};

std::source_location src_clone(std::source_location a = std::source_location::current())
{
    return a;
}

std::source_location src_make()
{
    return std::source_location::current();
}

int main()
{
    const auto r0 = src_rec();
    const auto r1 = src_rec(0);
    const auto r2 = src_rec(0.0);
    const auto s0 = std::source_location::current();
    const auto s1 = src_clone(s0);
    const auto s2 = src_clone();
    const auto s3 = src_make();

    std::println("#{1} {0} {2}", "r0", r0.srcl.line(), r0.srcl.function_name());
    std::println("#{1} {0} {2}", "r1", r1.srcl.line(), r1.srcl.function_name());
    std::println("#{1} {0} {2}", "r2", r2.srcl.line(), r2.srcl.function_name());
    std::println("#{1} {0} {2}", "s0", s0.line(), s0.function_name());
    std::println("#{1} {0} {2}", "s1", s1.line(), s1.function_name());
    std::println("#{1} {0} {2}", "s2", s2.line(), s2.function_name());
    std::println("#{1} {0} {2}", "s3", s3.line(), s3.function_name());
}

可能的输出:

#31 r0 int main()
#13 r1 src_rec::src_rec(int)
#16 r2 src_rec::src_rec(double)
#34 s0 int main()
#34 s1 int main()
#36 s2 int main()
#26 s3 std::source_location src_make()

参阅

构造具有实现定义值的 source_location 对象
(公开成员函数)
[static]
获取当前调用栈或其指定部分
( std::basic_stacktrace<Allocator> 的公开静态成员函数)