§The Annotated C++ StandardC++ 标准注疏 中文
17.8

Source location

std::source_location combines the consteval current() with the rule that default arguments are evaluated at the call site, letting ordinary functions record the caller's file, line and function name; plus the rules for each field's value and the convention for default member initializers.

Key points

  • Written as a function's default argument, std::source_location::current() gives the caller's location, not the location of the function declaration. Written in the function body, it gives that line of the body.
  • Written as a default member initializer, it gives the location of the constructor or aggregate initialization that uses it.
  • The line number and file name agree with __LINE__ and __FILE__ and are affected by #line; the format of the column number and function name is implementation-defined.
  • The two string fields are never null pointers; outside any function, the function name is an empty string.

Recording the caller's location#

C++srcloc-log.cpp✓ well-formedgodbolt ↗
#include <cstdio>
#include <source_location>

void log(const char* msg,
         std::source_location loc = std::source_location::current()) {
  std::printf("%s:%u [%s] %s\n", loc.file_name(), unsigned(loc.line()),
              loc.function_name(), msg);
}

template<class T> void tf(T) { log("in template"); }

int main() {
  log("hello");   // records this line, not where log is declared
  tf(1.0);
  [] { log("lambda"); }();
}

Output with Clang 23:

srcloc-log.cpp:13 [int main()] hello
srcloc-log.cpp:10 [void tf(T) [T = double]] in template
srcloc-log.cpp:15 [auto main()::(lambda)::operator()() const] lambda

C-style logging macros record the location with __FILE__, __LINE__ and __func__, but these are only useful inside a macro. Written as an ordinary function's default argument int line = __LINE__, the macro expands at the declaration, and what is recorded is always the declaration's line.

std::source_location (C++20, P1208R6) solves this. It relies on two rules: default arguments are evaluated at each call, at the call site ([dcl.fct.default]); and current() is a consteval function, evaluated at compile time on every call, recording the location where it is evaluated ([expr.const.imm]). Together, current() records the call site.

Shape of the class [support.srcloc.class.general]#

C++
struct source_location {
  static consteval source_location current() noexcept;
  constexpr source_location() noexcept;
  constexpr source_location(const source_location&) noexcept = default;
  constexpr source_location& operator=(const source_location&) noexcept = default;

  constexpr uint_least32_t line() const noexcept;
  constexpr uint_least32_t column() const noexcept;
  constexpr const char* file_name() const noexcept;
  constexpr const char* function_name() const noexcept;
private:
  uint_least32_t line_, column_;              // exposition only
  const char* file_name_; const char* function_name_;   // exposition only
};

<source_location> defines only this one class ([source.location.syn]), and the whole header is freestanding.

¶1 source_location meets semiregular (default constructible and copyable), and is_nothrow_swappable_v<source_location> is true. Note 1 explains that the intent is for it to be small and fast to copy; whether its copy and move operations are trivial is unspecified.

¶2 file_name_ and function_name_ always point to a null-terminated byte string, never a null pointer, so they can be passed straight to printf("%s").

¶3 After a copy or move, the new object has the same four field values as the original. The string fields compare equal by strcmp; the pointers need not be the same.

libc++ stores a single pointer

The four exposition-only members are just a way of describing the specification. libc++'s source_location has a single member pointing to a static structure generated by the compiler, which holds the file name, function name, line and column, so sizeof(std::source_location) is 8 in our tests. That structure is produced by Clang's built-in __builtin_source_location(), and the names of the structure and its fields are hard-coded in the compiler; the library and the compiler are directly coupled here.

The value of current() [support.srcloc.cons]#

¶1.1 When current() is invoked in the ordinary way (the postfix expression being called is a possibly parenthesized id-expression naming current), it returns a source_location with an implementation-defined value. The value should be affected by #line in the same way as __LINE__ and __FILE__ ([cpp.line]). The field values:

Field Value
line_ The presumed line number ([cpp.predefined]), starting from 1; 0 is encouraged when the line number is unknown
column_ Implementation-defined, an offset from the start of the line of some kind, starting from 1; 0 is encouraged when unknown
file_name_ The presumed name of the current source file ([cpp.predefined])
function_name_ The name of the current function, like __func__ ([dcl.fct.def.general]); an empty string outside any function

The format of the function name is implementation-defined. Clang and GCC actually give a form with the signature, like __PRETTY_FUNCTION__; see the output at the top. The column number is also implementation-defined, so don't expect different compilers to agree.

C++srcloc-line.cpp✓ well-formedgodbolt ↗
#include <cstdio>
#include <source_location>

constexpr auto here = std::source_location::current();
static_assert(here.line() == 4);
static_assert(here.function_name()[0] == '\0');  // not in a function: empty string

int main() {
#line 1000 "fake.cpp"
  auto loc = std::source_location::current();
  std::printf("%s:%u\n", loc.file_name(), unsigned(loc.line()));
}

The program prints fake.cpp:1000. All the observer functions are constexpr, so their results can be used in static_assert ([support.srcloc.obs]).

¶1.2 When invoked in any other way, the returned fields have valid but unspecified values. This is a fallback clause that portable programs hardly ever hit: current is a consteval function and its address can't be taken outside an immediate invocation; Clang 23 reports "cannot take address of consteval function" for &std::source_location::current.

¶4 The default constructor initializes the fields to valid but unspecified values. In libc++, the two strings are empty and the line and column are 0.

Default arguments and default member initializers (¶2)#

The standard says

Any call to current that appears as a default argument ([dcl.fct.default]), or as a subexpression thereof, should correspond to the location of the invocation of the function that uses the default argument ([expr.call]).

¶2 When current() appears as a default argument or a subexpression of one, it should correspond to the location of the invocation of the function that uses the default argument. When it appears as a default member initializer ([class.mem.general]), it should correspond to the location of the constructor definition or aggregate initialization that uses the initializer.

Both agree with the core language: default arguments are evaluated at the call site, and default member initializers are evaluated when a constructor uses them. The wording says "should", a recommendation to implementations, which all mainstream implementations follow.

C++srcloc-member.cpp✓ well-formedgodbolt ↗
#include <cstdio>
#include <source_location>

struct S {
  std::source_location where = std::source_location::current();
  int x = 0;
  S() {}          // a.where points to this line (line 7)
  S(int v) : x(v) {}   // b.where points to this line (line 8)
};
struct Agg { std::source_location where = std::source_location::current(); };

int main() {
  S a, b(1);
  Agg g{};        // aggregate initialization: points to this line (line 14)
  std::printf("%u %u %u\n", unsigned(a.where.line()),
              unsigned(b.where.line()), unsigned(g.where.line()));
}

This prints 7 8 14 in our tests. The standard's example in paragraph 3 also shows another point: when a source_location is passed explicitly, as in f(c), what is recorded is c's own location.

Wrapping it in a function breaks it

C++
std::source_location where() { return std::source_location::current(); }
void log(const char* msg, std::source_location loc = where());
where() always returns the line in its own body. The default argument where() is indeed evaluated at the call site, but current() is called in the body of where. Only when current() itself appears directly in the default argument does it correspond to the call site.

Variadic templates have no room for the default argument

template<class... Args> void log(const char* fmt, Args&&... args, std::source_location loc = std::source_location::current()) doesn't work: a parameter after a function parameter pack can't be deduced, and the pack swallows all the arguments in a call. The common technique is to put the location into the type of the first parameter:

C++
struct fmt_loc {
  const char* fmt;
  std::source_location loc;
  fmt_loc(const char* f,
          std::source_location l = std::source_location::current())
    : fmt(f), loc(l) {}
};
template<class... Args> void log(fmt_loc f, Args&&... args);

When log("x = {}", x) is called, "x = {}" implicitly converts to fmt_loc, and the converting constructor's default argument is evaluated at the call site.

In this clause

The authoritative text is eel.is/c++draft/support.srcloc (working draft 2026-08-23, commit c7015b485c). These are study notes that explain rather than quote; ¶ numbers follow the draft. Translated from the Chinese original. Last updated 2026-10-19.