问题
I've just been researching the use and benefits/pitfalls of the C++ keyword inline
on the Microsoft Website and I understand all of that.
My question is this: if the compiler evaluates functions to see if inlining them will result in the code being more efficient and the inline
keyword is only a SUGGESTION to the compiler, why bother with the keyword at all?
EDIT: A lot of people are moaning about my use of (Also fixed the website link)__inline
instead of inline
. I'd like to point out that __inline
is the Microsoft specific one: so it's not wrong, it's just not necessarily what you're used to.
EDIT2: Re-formatted the question to indicate the inline
keyword (used across all of C++) instead of the Microsoft-specific __inline
keyword.
回答1:
Firstly, it is not __inline
, but inline
.
Secondly, the effect inline
has within the One Definition Rule is undeniably significant. It allows you to define the functions multiple times and have the compiler to handle it.
Thirdly, with regard to the actual inilining this is your way to express your opinion about that function not only to the compiler but also to those who might read your code later. In many cases it is a way to let off the steam, so to say. Basically, it is a way for you to tell the others and yourself: "I feel that this function is too small (or too specialized) to justify the calling overhead, so don't hold me responsible for this travesty. I did all I could. If not for your stupid company-wide coding standard, I would've made it a macro". In that regard it is a sort of formalized comment.
Fourthly, seeing that you used an implementation-specific spelling of the keyword, I'd note that some implementations offer you alternative keywords that give you the opportunity to be more... er... persuasive in your desire to have that function inlined. In MS compiler that would be __forceinline
.
回答2:
The keyword is inline
and not __inline
.
inline
is not a mere suggestion it is the best standard compliant way to include a function definition in a header file without breaking the one definition rule.
回答3:
Judging from the documentation in MSDN, I think it's a purely pragmatic thing, mostly for the benefit of C programs.
Since inline
is a valid identifier name in C, another keyword is needed in C.
Personally, I would only consider using it if my source code could end up being shared between C and C++ programs (in Visual Studio, obviously).
来源:https://stackoverflow.com/questions/17325911/why-bother-with-the-inline-keyword-in-c