Search code examples
c++compiler-theorycompiler-optimization

Does the compiler decide when to inline my functions (in C++)?


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?


Solution

  • 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.