如果在 C++ 中没有事先声明就定义了自由函数,那么自由函数是否会隐式内联?
以下自由函数在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这取决于你所说的内联是什么意思。 编译器可以通过将发出的代码内嵌在调用站点来优化任何函数。 但是,如果您的意思是您询问的代码的行为是否像已声明的那样:
那么答案是否定的。 如果将代码放置在两个不同的编译单元中并构建可执行文件,则会出现多个定义错误。 如果您明确地将函数标记为“内联”,则不会。
对于模板函数,编译系统的某些部分将确保同一模板的多个实例不会导致多个定义错误。
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:
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.
不,它不是隐式内联的。 编译器无法知道另一个模块是否会使用此函数,因此它必须为其生成代码。
这意味着,例如,如果您像标头中那样定义函数并包含标头两次,您将收到有关多个定义的链接器错误。 显式
内联
修复了这个问题。当然,如果编译器认为高效,仍然可以内联该函数,但这与显式内联不同。
模板函数是隐式内联的,因为它们不需要内联来防止多个定义错误。 我也不认为编译器被迫内联这些,但我不确定。
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.它可能是内联的,具体取决于编译器是否决定使其内联。
It might be inlined, depending on if the compiler decides to make it inline or not.