Consider the following class:
template <class T>
struct Test
{
Test() {
if (!f) {
f = []() { std::cout << "it works\n"; };
initialized = true;
}
}
static void check() {
if (f) f();
else std::cout << "f is empty\n";
}
T x{};
inline static std::function<void()> f;
inline static bool initialized = false;
};
An object of such class, if declared globally (Yes, I know it's a bad practice to use global variables), seems to empty the function f
after it is initalized. The following example demonstrates this:
Test<double> t;
int main()
{
t.x = 1.5;
std::cout << "t.x = " << t.x << "\n";
std::cout << std::boolalpha << "initalized: " << Test<double>::initialized << "\n";
Test<double>::check();
return 0;
}
This prints:
t.x = 1.5
initalized: true
f is empty
I expected Test<double>::check();
to print it works
.
However, the above example works as expected, when I do either of the following:
- declare
t
withinmain()
- do not use template for
Test
(just replaceT
withdouble
for example) - make
f
andcheck()
be not static - use plain function pointer instead of
std::function
Does anyone know why this happens?
if (!f) { f = ... }
condition. – Streaming