如果函数是在头文件中定义的,则inline关键字是否有意义?(Is inline keyword meaningful if function is defined in header file?)

编程入门 行业动态 更新时间:2024-10-25 23:34:48
如果函数是在头文件中定义的,则inline关键字是否有意义?(Is inline keyword meaningful if function is defined in header file?)

所有代码从我读过的内容来看,A1和A2是相同的,但如果A3与A2完全相同,我不会这么做。 我知道代码将被编译,因为所有的A类都被模板化了。

注意:所有的类和方法声明都在.h文件中。

template <typename _Ty> class A1 { public: A1(); void foo() { ... } }; template <typename _Ty> class A2 { public: A2(); void foo(); }; template <typename _Ty> inline void A2<_Ty>::foo() { ... } template <typename _Ty> class A3 { public: A3(); void foo(); }; template <typename _Ty> void A3<_Ty>::foo() { ... } // note: No inline keyword here.

PS我已经看到了这个问题的变种在stackoverflow,但不是这个确切的问题。

All code From what I've read, A1 & A2 are identical, but I don't if A3 is identical to A2. I know the code will compile since all of the A classes are tmemplated.

Note: All of the class & method declarations are in a .h file.

template <typename _Ty> class A1 { public: A1(); void foo() { ... } }; template <typename _Ty> class A2 { public: A2(); void foo(); }; template <typename _Ty> inline void A2<_Ty>::foo() { ... } template <typename _Ty> class A3 { public: A3(); void foo(); }; template <typename _Ty> void A3<_Ty>::foo() { ... } // note: No inline keyword here.

P.S. I've seen variants of this question on stackoverflow, but not this exact question.

最满意答案

是的,这是有意义的,但与模板结合时效果不佳。

inline关键字的主要作用是告诉编译器该函数可能在多个编译单元中以相同的定义出现,所以它需要被标记为链接器的“选择一个”(所以你不会得到多重定义错误)。 模板已具有此功能。

inline还向编译器提示您认为该函数应该内联,但编译器通常会自行对内联优化做出最终决定。

Yes, it's meaningful, but doesn't have much effect when combined with templates.

The major effect of the inline keyword is to tell the compiler that this function may appear with the same definition in multiple compilation units, so it needs to be flagged as "select-one" for the linker (so you don't get multiple definition errors). Templates already have this feature.

inline also is a hint to the compiler that you think the function should be inlined, but the compiler usually makes the final decision on inlining optimizations on its own.

更多推荐

本文发布于:2023-08-06 14:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1451158.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是在   有意义   函数   头文件   定义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!