簡體   English   中英

為什么在C ++中構造一個靜態thread_local對象兩次?

[英]Why is a static thread_local object in C++ constructed twice?

這段代碼:

#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;
}

具有以下輸出:

Singl() 2
Singl() 2
1
~Singl() 2
~Singl() 2

我正在使用mingw-w64 gcc7.2 POSIX線程在Windows下編譯和運行。

Coliru具有不同的輸出: http ://coliru.stacked-crooked.com/a/3da415345ea6c2ee

這是什么? 我的工具鏈/編譯器出問題了,還是應該這樣? 為什么在同一線程上有兩個thread_local對象(或構造兩次?)?

您的編譯器或工具鏈可能有問題。

在Linux上使用clang ++ 8和g ++ 8.2(確切地說是Devuan ASCII)時,線程局部變量僅構造一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM