c ++ 11全局初始化顺序和thread_local

时间:2014-10-24 20:19:17

标签: c++ c++11 static initialization thread-local-storage

当使用gcc 4.8.1运行以下内容时,使用thread_local关键字时会触发断言。删除thread_local时,不会触发断言。有人知道为什么吗?有一些未定义的全局排序,但我希望buf_在分配ptr_之前有一个有效的地址。只需删除关键字thread_local,它就适用于我。

输出:

$ ./ThreadLocal 
 Running Tester 
ThreadLocal: main.cpp:13: int main(): Assertion `buf == ptr' failed.
Aborted (core dumped)

Output when removing thread_local keyword
 Running Tester 

Test.hpp

 #include <iostream>
 #include <cassert>

template <typename std::size_t N>
struct Mem
{
    Mem() noexcept: ptr_(buf_)
    {}

    char * getBuf() { return buf_; }
    char * getPtr() { return ptr_; }

private:
    char buf_[N];
    char * ptr_;
};



template <typename std::size_t N>
struct Tester
{
    Tester()
    {
        std::cout << " Running Tester " << std::endl;
    }

    char * getPtr() { return _mem.getPtr(); }
    char * getBuf() { return _mem.getBuf(); }

private:
    static thread_local Mem<N> _mem;
}; 

main.cpp

#include <iostream>
#include "Test.hpp"

template <typename std::size_t N>
thread_local Mem<N> Tester<N>::_mem;

int main()
{
    Tester<500> t;
    char * ptr  = t.getPtr();
    char * buf = t.getBuf();

    assert( buf == ptr );
}

1 个答案:

答案 0 :(得分:3)

它看起来像GCC中的一个错误。显然Tester::_mem根本没有被初始化。 GCC 4.9.0 does the same,但clang 3.5.0 works fine

使_mem不依赖于模板参数makes GCC crash

最后,将Tester设为非模板类​​makes GCC work at last

更新:这些似乎是GCC中的known bugs