constexpr
give the C++ compilers a hint that the function or the variable need to be valid during the compile time. It is by design thread-safe.
Using on Variable
It is essentially the same with declaring a const
variable that is the variable should not be change in either compile time or runtime. This make the variable avoid all #downside of concurrency.
Using on Function
constexpr
force the function to resolve each dependency at compile time. Any attempts on extending (static
and thread_local
) the variable’s lifetime or using such variables in the scope of the function is rejected. In addition, constexpr
function cannot have side effect.
This eventually makes the function #pure.
Since constexpr
function is evaluated in compile time, it makes the function more efficient compare to its non-constexpr
counterpart.