Reputation: 9196
I tried the following first variant using GCC10 in C++20 mode:
consteval std::experimental::source_location there()
{
return std::experimental::source_location::current(); // Line 3
}
void f(const std::experimental::source_location& a = there()) // Line 6
{
std::cout << a.line() << std::endl;
}
int main(int pArgc, char* pArgv[])
{
std::cout << there().line() << std::endl; // Line 13
f(); // Line 14
return 0;
}
I expected the following output:
13
14
but I got:
3
3
Then I tried the following second variant:
consteval std::experimental::source_location there(const std::experimental::source_location& a = std::experimental::source_location::current())
{
return a; // Line 3
}
void f(const std::experimental::source_location& a = there()) // Line 6
{
std::cout << a.line() << std::endl;
}
I expected the following output:
13
14
but I got:
13
6
Why does the code behave that way? Is there a way to make it behave as expected without using a pre-processor macro?
Update: The second variant with 'constexpr' or 'inline' instead of 'consteval' works fine with most recent GCC. So the remaining question is: Why doesn't 'consteval' work as well? I was told this isn't a standard issue but an implementation topic so I will re-tag this question as GCC.
Upvotes: 3
Views: 626
Reputation: 9196
I turned out second variant is correct. On current GCC 12 it works fine.
Upvotes: 0
Reputation: 1814
source_location::current()
always gives you the exact location from where it is called. The observed bahaviour is exactly how it should work.
Default function arguments are evaluated on the call-site. This is why the first call in the second example returns "13". This is also the only way how you should use source_location
when wrapped in a function call (it doesn't make much sense otherwise).
Upvotes: 3