What is the criterion to be inline [duplicate]

2019-09-02 03:36发布

This question already has an answer here:

How does compiler calculate which function should be inline since inline request is not obligatory? What kind of functions should I make inline?

Extra question. Can I make an inline call?

void func{} // normal (not-inline) function

int main()
{
  func();           // normal call
  // inline func(); // inline call
  return 0;
}

标签: c++ inline
3条回答
The star\"
2楼-- · 2019-09-02 03:48

When you are mark a function as inline you are advising the compiler that this function should be inlined. On (good) compilers this neither guarantees it will be, nor does it's absence guarantee it won't be.

All inlining a function does is replace the call to the function with the body of the code. So while you can't suggest where the compiler should inline the function, you obviously could actually paste the code in (or use a macro to ensure the code stays the same). But you'd need a really good/odd reason to do this.

In general, mark small functions as inline if you wish, but otherwise leave it to the compiler.

查看更多
做自己的国王
3楼-- · 2019-09-02 03:50

What inline does is recommend to the compiler to replace any calls to this function with the actual code of the function, as T. Kiley said a while ago. The compiler does not have to do this, but if it does, this is what happens:

If you have this function:

inline int addtwo(int i)
{
return i+2;
}

the compiler will replace all statements like

cout<<addtwo(x)<<endl;

with

cout<<(x+2)<<endl;

If your function was longer than a few lines, the finished executable size would increase, since every call would be replaced with the entire code of the function. (what other drawbacks are there?)

inline is for functions that are trivially short (1 line).

查看更多
不美不萌又怎样
4楼-- · 2019-09-02 04:08

How does compiler calculate which function should be inline since inline request is not obligatory?

  • (from wiki) In various versions of the C and C++ programming languages, an inline function is a function upon which the compiler has been requested to perform inline expansion. In other words, the programmer has requested that the compiler insert the complete body of the function in every place that the function is called, rather than generating code to call the function in the one place it is defined. Compilers are not obligated to respect this request.

    In C++, you can use __forceinline keyword allow the programmer to force the compiler to inline the function, but indiscriminate use of __forceinline can result in larger code (bloated executable file), minimal or no performance gain, and in some cases even a loss in performance.

What kind of functions should I make inline?

Can I make an inline call?

  • You cannot make an inline call as inline can only used in function declaration, not calling. You just need to call a pre-defined inline function as normal functions.
查看更多
登录 后发表回答