3

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

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

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

4

1 回答 1

0

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

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

于 2019-10-13T17:42:03.200 回答