This code:
#include <iostream>
#include <thread>
#include <mutex>
struct Singl{
Singl(Singl const&) = delete;
Singl(Singl&&) = delete;
inline static thread_local bool alive = true;
Singl(){
std::cout << "Singl() " << std::this_thread::get_id() << std::endl;
}
~Singl(){
std::cout << "~Singl() " << std::this_thread::get_id() << std::endl;
alive = false;
}
};
static auto& singl(){
static thread_local Singl i;
return i;
}
struct URef{
~URef(){
const bool alive = singl().alive;
std::cout << alive << std::endl;
}
};
int main() {
std::thread([](){
singl();
static thread_local URef u;
}).join();
return 0;
}
It has the following output:
Singl() 2
Singl() 2
1
~Singl() 2
~Singl() 2
I compile and run on Windows with MOSW-W64 GCC7.2 POSIX streams.
Coliru has different results: http://coliru.stacked-crooked.com/a/3da415345ea6c2ee
What is it, is something wrong with my toolbox / compiler, or is it the way it should be? Why do I have two thread_local objects (or constructed twice?) In the same thread ???
source
share