问题
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