gpt4 book ai didi

c++ 17内联+ thread_local vs thread_local

转载 作者:行者123 更新时间:2023-12-03 10:05:15 27 4
gpt4 key购买 nike

我想知道以下两个声明之间的区别是什么,如果两者都写在一个头文件中:

inline thread_local MyClass obj1;  // inline with thread_local
thread_local MyClass obj2; // no inline

如 C++17 中所述,向变量添加内联会强制所有翻译单元看到该变量的相同地址。这是否意味着 obj2 是可能的?在不同的翻译单元中获得不同的地址值?我们应该使用 obj1 突出显示什么情况而不是 obj2 ?

最佳答案

如果在多个编译单元中包含这个头文件,你会得到多个 obj2 的定义。 .但是obj1会正常工作,因为链接器将保证只存在一个定义,并且所有编译单元将使用相同的定义(因此使用相同的地址)。
所以,你的代码应该使用 externobj2并在单个编译单元中定义它。但是inline已经为您做了这些 obj1 .

Does this mean it's possible for obj2 to get different address valuesin different translation units?


在那种特殊情况下,不,因为它不会编译。但是如果你加上 staticobj2 ,您将获得每个编译单元一个地址。

What would be the situation to highlight we should use obj1 ratherthan obj2?


你永远不应该使用 obj2像这样, obj1是正确的方法。如果你想避免 inline ,您可以使用 externobj2 .

关于c++ 17内联+ thread_local vs thread_local,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56979608/

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