This question (and the code) is inspired by Jason Turner's C++ Weekly episode: Stop Using constexpr
(And Use This Instead!)
Assume the code below (compiler explorer)
My understanding is that when declaring a function local variable as static constexpr
I am guaranteed that the variable is initialized only once (static), and without any thread safety overhead normally required if the compiler cannot prove single thread access (due to it being constexpr).
But does the c++ standard guarantee this? Is there anywhere in the standard to point to that ensures me that the line static constexpr auto arr = getArr();
will never result in the compiler adding a mutex or other sort of thread protectiong?
Neither Jason Turner's episode, or this stackoverflow question mentions the thread safety overhead that can come with local static variables, and that is the main point I am looking for a definite answer to - preferably by pointing to the standard.
So to be clear: Can I be sure that arr
in the getVal()
function is initalized at compile time, without the need for any thread synchronization?
constexpr auto getArr()
{
std::array<int,10> arr;
for (int i = 0; i < 10; ++i) {
arr[i] = i*2;
}
return arr;
}
auto getVal(int i)
{
static constexpr auto arr = getArr();
return arr[i] + 1;
}
int main()
{
return getVal(4);
}