Does the compiler decide when to inline my functio

2019-01-15 08:16发布

I understand you can use the inline keyword or just put a method in a class declaration ala short ctor or a getter method, but does the compiler make the final decision on when to inline my methods?

For instance:

inline void Foo::vLongBar()
{
   //several function calls and lines of code
}

Will the compiler ignore my inline declaration if it thinks it will make my code inefficient?

As a side issue, if I have a getter method declared outside my class like this:

void Foo::bar() { std::cout << "baz"; }

Will the compiler inline this under the covers?

9条回答
我命由我不由天
2楼-- · 2019-01-15 08:49

As per my knowledge, compiler will automatically make a function you declared inline (or wrote inside a class declaration) non -inline if it finds a loop like for, while etc. This is one example where compiler has the last say in inline functions.

查看更多
趁早两清
3楼-- · 2019-01-15 08:57

Whether or not a fiunction is inlined is, at the end of the day, entirely up to the compiler. Typically, the more complex a function is in terms of flow, the less likely the compiler is to inline it. and some functions, such as recursive ones, simply cannot be inlined.

The major reason for not inlining a function is that it would greatly increase the overall size of the code, preventing iot from being held in the processor's cache. This would in fact be a pessimisation, rather than an optimisation.

As to letting the programmer decide to shoot himself in the foot, or elsewhere, you can inline the function yourself - write the code that would have gone in the function at what would have been the function's call site.

查看更多
唯我独甜
4楼-- · 2019-01-15 09:00

Yes, the compiler has the final decision. In VS you can even inline recursive functions into specified depth ;)

#pragma inline_depth( [0... 255] )
查看更多
登录 后发表回答