Inline Functions/Methods

家住魔仙堡 提交于 2019-12-10 19:41:09

问题


Statement: "Inline-functions must be defined before they are called."

Is this statement correct?

[EDIT]

The question is originally in german:
Inline-Funktionen müssen vor ihrem Aufruf definiert sein.

Maybe it helps anybody...


回答1:


Yes it is correct but only partly.It maybe re-framed correctly as follows:

"Inline-functions must be defined in every translation unit(but not necessarily before) in which they are called."

C11++ Standard: §7.1.2.4

An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case.[Note: A call to the inline function may be encountered before its definition appears in the translation unit. —end note]

Why this rationale?

When you declare a function inline basically You are telling the compiler to (if possible)replace the code for calling the function with the contents of the function wherever the function is called. The idea is that the function body is probably small and calling the function is more overhead than the body of the function itself.

To be able to do this the compiler needs to see the definition while compiling the code, where the function is being called. Usually, this is done by adding the definition of the function in an header with the inline specifier and then including the header file in every cpp file where the function is to be called.




回答2:


No. C++11 draft n3242 more clearly than the earlier specifications states in 7.1.2 subsection 4;

An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case (3.2). [ Note: A call to the inline function may be encountered before its definition appears in the translation unit. — end note ]




回答3:


The statement makes no sense: a function that is inlined is no longer called, the code is simply there in the current function (it has been "inlined"). So no, I'd say it's not correct.



来源:https://stackoverflow.com/questions/9853318/inline-functions-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!