内联函数的局部static / thread_local变量? [英] Local static/thread_local variables of inline functions?
问题描述
如果我在不同翻译单元中定义的内联函数中具有静态局部变量或thread_local局部变量,则在最终程序中是否可以通过标准保证它们具有相同的地址?
If I have a static local variable or thread_local local variable that is within an inline function that is defined in different translation units, in the final program are they guaranteed by the standard to have the same address?
// TU1:
inline int* f() { static int x; return &x; }
extern int* a;
void sa() { a = f(); }
// TU2:
inline int* f() { static int x; return &x; }
extern int* b;
void sb() { b = f(); }
// TU3:
int *a, *b;
void sa();
void sb();
int main() { sa(); sb(); return a == b; }
以上内容始终返回1吗?
Will the above always return 1?
推荐答案
是的,它始终是同一对象。通过[dcl.fct.spec] / 4:
Yes, it's always the same object. By [dcl.fct.spec]/4:
一个内嵌
函数外部链接在所有翻译单元中应具有相同的地址。
外部内联
函数中的静态
局部变量始终引用同一对象。在extern内联
函数主体内定义的类型在每个翻译单元中都是相同的类型。
An
inline
function with external linkage shall have the same address in all translation units. Astatic
local variable in anextern inline
function always refers to the same object. A type defined within the body of anextern inline
function is the same type in every translation unit.
这篇关于内联函数的局部static / thread_local变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!