对于在头文件中实现的函数,静态对内联 [英] static vs inline for functions implemented in header files

查看:94
本文介绍了对于在头文件中实现的函数,静态对内联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为C ++中的 inline 的方式是链接/范围界定。我把它放在与全局对象的 extern static 相同的篮子中。

The way I think of inline in C++ is for linkage/scoping. I put it in the same basket with extern and static for global objects.

通常对于在头文件中实现的函数,我的解决方案是使其静态:

Typically for a function implemented in a header file, my go-to solution would be to make it static:

// In Foo.h
static void foo()
{
    // Do stuff...
}

但是,我相信这也是有效的,似乎没有违反ODR:

However, I believe this is also valid and does not seem to violate ODR:

// In Foo.h
inline void foo()
{
    // Do stuff...
}

两者之间的语义差异是什么?另外,我不确定C ++标准的哪些领域将解释确切的差异,或者如果它只是未定义和差异在于实现。

What are the semantic differences between the two? Also I'm not exactly sure what areas of the C++ standard would explain exact differences, or if it's just undefined and differences lie with the implementation.

推荐答案

inline 完全符合您的要求:请禁用此功能的ODR规则,以便每个翻译单位可以函数的定义。

inline conveys exactly what you want: "please suppress the ODR rule for this function, so that each translation unit can (and must) supply its own copy of the function's definition".

然后,编译器将内联调用函数,或者将来自不同TU的函数定义合并在一起(这样,另一方面,

The compiler will then either inline calls to the function, or merge together the function definitions from different TU's (so that the resulting function exists once in the executable).

static 告诉编译器生成在每个翻译单元中定义它的功能,而不是共享它。所以你最终得到了任意数量的技术上分离的函数存在于结果可执行文件中。

static, on the other hand, tells the compiler to generate the function in every translation unit where it is defined, and just not share it. So you end up with an arbitrary number of technically separate functions existing in the resulting executable.

简而言之,如果你使用 static ,那么在不同的翻译单元中获取函数的地址将返回不同的地址(因为你告诉编译器在每个TU中生成一个函数),但是如果你使用 inline ,它们会显示相同的地址(因为您要定义一个函数,只是告诉编译器将多个定义合并在一起)。

In a nutshell, if you use static, then taking the address of the function in different translation units will return different addresses (because you're telling the compiler to generate a function in each TU), but if you use inline, they'll show the same address (because you're defining one function, and just telling the compiler to merge the many definitions together).

这篇关于对于在头文件中实现的函数,静态对内联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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