我在销毁 thread_local 静态对象时遇到问题。
#include <iostream>
#include <thread>
struct UsesLoc {
UsesLoc() {
loc.counter++;
}
struct Loc {
Loc() {
std::cout << "I am at " << this << " and counter is " << counter << std::endl;
}
~Loc() {
std::cout << "I was at " << this << " and counter is " << counter << std::endl;
}
int counter = 0;
};
static thread_local Loc loc;
};
thread_local UsesLoc::Loc UsesLoc::loc;
int main()
{
{
UsesLoc usesloc;
std::cout << "loc is at " << &UsesLoc::loc << " and counter is " << UsesLoc::loc.counter << std::endl;
}
return 0;
}
正如预期的那样,在https://coliru.stacked-crooked.com/a/e8bcfdaffa6a6da7上编译和运行显示 thread_local 对象始终位于同一位置,计数器值为 (0,1,1):
I am at 0x7f9dc817673c and counter is 0
loc is at 0x7f9dc817673c and counter is 1
I was at 0x7f9dc817673c and counter is 1
相反,当我在本地使用 MinGW 编译并运行时,我会得到,例如,
I am at 0x507874 and counter is 0
loc is at 0x507874 and counter is 1
I was at 0x7efdd000 and counter is 2686552
显然,在不同内存位置的未初始化对象被销毁。
我是否监督了任何不确定的事情?如何确保销毁正确的对象?