thread_local静态类在程序退出时在无效地址处被破坏

问题描述 投票:3回答:1

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

显然,位于不同存储位置的未初始化对象被破坏。

我是否监督了不确定性?如何确保销毁了正确的物体?

我在销毁thread_local静态对象时遇到问题。 #include #include struct UsesLoc {UsesLoc(){loc.counter ++; } struct Loc {...

c++ c++14 thread-local static-initialization destruction
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.