为什么类成员函数是内联的?
我想我的问题以前在这里被问过,我确实阅读了它们,但仍然有点困惑,因此要求说清楚.
I think my question has been asked here before, I did read them but still little confused and therefore asking to make it clear.
C++ 标准规定所有在类定义中定义的成员函数都是内联的
我还听说编译器可以忽略函数的内联.在上述情况下是这样吗?或者如果在类定义中定义它总是内联?
I have also heard that compiler can ignore inlining of a function. Will that be true in the above case or it will be always inlined if defined inside class definition?
另外,这个设计背后的原因是什么,让所有在类定义中定义的函数都内联?内联与源文件和头文件有什么关系?
Also, what was the reason behind this design, making all functions defined inside class definition inline? And what inlining has to do with source and header files?
更新:所以如果不被内联,就应该总是在类之外定义它们的函数,对吧?
Update: So one should always define their functions outside class if not to be inlined, right?
JohnB 的更新 2: 在类定义中声明的两个函数永远不能互相调用,因为它们都必须包含另一个函数的整个主体.在这种情况下会发生什么?(Emilio Garavaglia 已经回答)
Update 2 by JohnB: Two functions declared inside class definition could never call each other as they would have to each contain the whole body of the other function. What will happen in this case? (Already answered by Emilio Garavaglia)
推荐答案
产生混淆是因为 inline 有两个作用:
Confusion arises because inline has two effects:
- 它告诉编译器函数代码可以在函数被调用的地方扩展,而不是有效地被调用.
- 它告诉编译器函数定义可以重复.
第 1 点是过时的",因为编译器实际上可以为所欲为,以优化代码.如果可以并且发现方便,它将始终内联"机器代码,如果不能,它将永远不会这样做.
Point 1. is "archaic" in the sense that the compiler can in fact do what it likes in order to optimize code. It will always "inline" machine code if it can and find convenient to do and it will never do that if it cannot.
Point 2. 是该术语的实际含义:如果您在标头中define
(指定主体)函数,由于标头可以包含在更多源中,因此您必须告诉编译器通知链接器定义重复,以便它们可以合并.
Point 2. is the actual meaning of the term: if you define
(specify the body) a function in the header, since a header can be included in more sources, you must tell the compiler to inform the linker about the definition duplicates, so that they can be merged.
现在,根据语言规范,自由函数(未在类主体中定义)默认情况下未定义为内联,因此在标题中定义类似
Now, by the language specification, free functions (not defined in class bodies) are by default not defined as inline, so defining in a header a thing like
void myfunc()
{}
如果header包含在多个源中,然后在同一个输出中链接,链接器会报多重定义错误,因此需要将其定义为
if the header is included in more sources, then linked in a same output, the linker will report a multiple definition error, hence the need to define it as
inline void fn()
{}
对于类成员,默认是相反的:如果你只是声明它们,它们不会被内联.如果您定义它们,它们将是内联的.
For class members, the default is the opposite: if you just declare them, they will not be inlined. If you define them, they will be inline.
所以标题应该是这样的
//header file
class myclass
{
public:
void fn1()
{} //defined into the class, so inlined by default
void fn2();
};
inline void myclass::fn2()
{} //defined outside the class, so explicit inline is needed
如果 myclass::fn2()
定义进入适当的来源,则必须丢失 inline
关键字.
And if myclass::fn2()
definition goes into a proper source, must lose the inline
keyword.
相关文章