Is there any trap in static constant field initialization order?
template <typename T>
struct constant_test {
static const T PI;
static const T FULL_CIRCLE;
static const T HALF_CIRCLE;
static const T DEG_TO_RAD;
};
template <typename T> const T constant_test<T>::PI = 3.141592653589f;
template <typename T> const T constant_test<T>::FULL_CIRCLE = 360.0f;
template <typename T> const T constant_test<T>::HALF_CIRCLE = constant_test<T>::FULL_CIRCLE / 2;
template <typename T> const T constant_test<T>::DEG_TO_RAD = constant_test<T>::PI / constant_test<T>::HALF_CIRCLE;
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {
// uncomment to make it work
// float test_ref = constant_test<float>::HALF_CIRCLE;
char buf[128];
sprintf_s(buf, 128, "Value: %f", constant_test<float>::DEG_TO_RAD);
OutputDebugStringA(buf); // prints "Value: 1.#INF00"
return 0;
}
An expression constant_test<float>::DEG_TO_RAD magically returns -Infinity
If i remove template parameter and make them only float then constant is evaluated correctly (0.017453)
If i add reference to HALF_CIRCLE constant then it's also evaluated correctly
I'm using MSVC 2013 SP 1.
Why? What i'm missing?
According to
there are the following types of initialization:
int x; in global scopeint x=1+2; where 1+2 is a constant expressionstd::vector<int> x{1, 2, 3}; in global scope, ortemplate<> std::vector<int> A<int>::x{1, 2, 3}; (explicit specialization)template<class T> std::vector<T> A<T>::x;See What is Unordered dynamic initialization, Partially-ordered dynamic initialization and Ordered dynamic initialization for what the terms mean.
In this case
template <typename T> const T constant_test<T>::PI = 3.141592653589f;
template <typename T> const T constant_test<T>::FULL_CIRCLE = 360.0f;
are constant initialization(s), and because they're floating-point type in this case they're not constexpr, according to c++ - Initializing constexpr with const: Different treatment for int and double - Stack Overflow.
template <typename T> const T constant_test<T>::HALF_CIRCLE = constant_test<T>::FULL_CIRCLE / 2;
template <typename T> const T constant_test<T>::DEG_TO_RAD = constant_test<T>::PI / constant_test<T>::HALF_CIRCLE;
are dynamic unordered initialization.
As such, the initialization order of the 2 last ones are not guaranteed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With