如果在 C++ 中没有事先声明就定义了自由函数,那么自由函数是否会隐式内联?

发布于 2024-07-26 17:49:36 字数 120 浏览 1 评论 0原文

以下自由函数在 C++ 中是否隐式内联,类似于在类定义中定义的成员函数如何隐式内联?

void func() { ... }

模板函数的行为方式是否相同?

Is the following free function implicitly inlined in C++, similar to how member functions are implicitly inlined if defined in the class definition?

void func() { ... }

Do template functions behave the same way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

╰つ倒转 2024-08-02 17:49:36

这取决于你所说的内联是什么意思。 编译器可以通过将发出的代码内嵌在调用站点来优化任何函数。 但是,如果您的意思是您询问的代码的行为是否像已声明的那样:

inline void func() { ... }

那么答案是否定的。 如果将代码放置在两个不同的编译单元中并构建可执行文件,则会出现多个定义错误。 如果您明确地将函数标记为“内联”,则不会。

对于模板函数,编译系统的某些部分将确保同一模板的多个实例不会导致多个定义错误。

It depends what you mean by inlined. A compiler can optimise any function by placing its emitted code inline at the call site. However, if you mean does the code you ask about behave as if it was declared:

inline void func() { ... }

then the answer is no. If you place your code in two different compilation units and build the executable, you will get multiple definition errors. If you explicitly mark the function as "inline", you will not.

Regarding template functions, then some part of the compilation system will see to it that multiple instantiations of the same template do not cause multiple definition errors.

未央 2024-08-02 17:49:36

不,它不是隐式内联的。 编译器无法知道另一个模块是否会使用此函数,因此它必须为其生成代码。

这意味着,例如,如果您像标头中那样定义函数并包含标头两次,您将收到有关多个定义的链接器错误。 显式内联修复了这个问题。

当然,如果编译器认为高效,仍然可以内联该函数,但这与显式内联不同。

模板函数是隐式内联的,因为它们不需要内联来防止多个定义错误。 我也不认为编译器被迫内联这些,但我不确定。

No, it's not implicitly inlined. The compiler has no way of knowing if another module will use this function, so it has to generate code for it.

This means, for instance, that if you define the function like that in a header and include the header twice, you will get linker errors about multiple definitions. Explicit inline fixes that.

Of course, the compiler may still inline the function if it thinks that will be efficient, but it's not the same as an explicit inlining.

Template functions are implicitly inlined in the sense that they don't require an inline to prevent multiple definition errors. I don't think the compiler is forced to inline those either, but I'm not sure.

一念一轮回 2024-08-02 17:49:36

它可能是内联的,具体取决于编译器是否决定使其内联。

It might be inlined, depending on if the compiler decides to make it inline or not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文