Search code examples
c++std-source-location

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?


Solution

  • 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