gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:19:40 25 4
gpt4 key购买 nike

您好,当使用 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

测试.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;
};

主要.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 );
}

最佳答案

这看起来像是 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 .

更新:这些似乎是known bugs在海湾合作委员会中。

关于c++11 全局初始化顺序和thread_local,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26555637/

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