Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::source_location guaranteed to reuse the same object?

My question is: If std::source_location::current() is called multiple times for the same location, is the std::source_location object guaranteed to be the same for every call?

In other words, given the below code:

#include <source_location>
#include <iostream>
#include <format>

void log(const std::source_location& location = std::source_location::current())
{
    std::cout << std::format("{}\n", static_cast<const void*>(&location));
}

void func()
{
    log();
}

int main()
{
    func();
    func();
    func();
}

Is each call of func() guaranteed to print the same address every time?

like image 665
Walter Svenddal Avatar asked Sep 01 '25 03:09

Walter Svenddal


1 Answers

No, of course not. std::source_location::current() returns by value, it can't guarantee that.

Here's a trivial counterexample: run on gcc.godbolt.org

#include <iostream>
#include <source_location>

void a(const std::source_location &loc = std::source_location::current())
{
    std::cout << &loc << '\n';
}

void b() {a();}
void c() {b();}
int main(){b(); c();}

For me this prints two different addresses:

0x7ffcc2b8a0c8
0x7ffcc2b8a0b8
like image 79
HolyBlackCat Avatar answered Sep 02 '25 17:09

HolyBlackCat