Local static/thread_local variables of inline functions?

只愿长相守 提交于 2020-01-12 04:41:07

问题


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

Will the above always return 1?


回答1:


Yes, it's always the same object. By [dcl.fct.spec]/4:

An inline function with external linkage shall have the same address in all translation units. A static local variable in an extern inline function always refers to the same object. A type defined within the body of an extern inline function is the same type in every translation unit.



来源:https://stackoverflow.com/questions/32172137/local-static-thread-local-variables-of-inline-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!