内联函数的局部static / thread_local变量? [英] Local static/thread_local variables of inline functions?

查看:343
本文介绍了内联函数的局部static / thread_local变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在不同翻译单元中定义的内联函数中具有静态局部变量或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. 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.

这篇关于内联函数的局部static / thread_local变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆