gpt4 book ai didi

c++ - thread_local 静态类在程序退出时在无效地址处被销毁

转载 作者:行者123 更新时间:2023-12-02 05:48:19 25 4
gpt4 key购买 nike

我在销毁 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

显然,不同内存位置的未初始化对象被销毁。

我是否监督过任何不确定的事情?如何确保正确的对象被销毁?

最佳答案

获得 hint from Ted Lyngmo 后这可能是一个编译器错误,我做了一些研究,这似乎确实是一个之前已经报告过的问题:

话虽这么说,代码是正确的,并且指向被破坏的对象的指针指向之前使用符合标准的编译器时构造的同一对象。

关于c++ - thread_local 静态类在程序退出时在无效地址处被销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58339548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com