I want do some thread registration in my class, so I decide to add a check for the the thread_local feature:
#include <iostream> #include <thread> class Foo { public: Foo() { std::cout << "Foo()" << std::endl; } ~Foo() { std::cout << "~Foo()" << std::endl; } }; class Bar { public: Bar() { std::cout << "Bar()" << std::endl; //foo; } ~Bar() { std::cout << "~Bar()" << std::endl; } private: static thread_local Foo foo; }; thread_local Foo Bar::foo; void worker() { { std::cout << "enter block" << std::endl; Bar bar1; Bar bar2; std::cout << "exit block" << std::endl; } } int main() { std::thread t1(worker); std::thread t2(worker); t1.join(); t2.join(); std::cout << "thread died" << std::endl; } The code is simple. My Bar class has a static thread_local member foo. If a static thread_local Foo foo is created, it means a thread is created.
But when I run the code, nothing in the Foo() prints, and if I remove the comment in Bar's constructor, which uses foo, the code works fine.
I tried this on GCC (7.4.0) and Clang (6.0.0) and the results are the same. I guess that the compiler discovered that foo is unused and do not generate an instance. So
- Did the compiler ignore the
static thread_localmember? How can I debug for this? - If so, why does a normal
staticmember not have this problem?