C++ – Usefulness of the ‘inline’ Feature

c++

There's two things about inlining:

  • The inline keyword will be ignored if the compiler determines that the function cannot be inlined.
  • There is a compiler optimization (on Visual Studio, I don't know about GCC) that tells the compiler to inline all functions where possible.

From this I conclude that I never need to bother about inlining. I just have to turn on the compiler optimization for the release build.

Or are there any situations where manually inlining would be preferred?

Best Answer

The inline keyword has two functions:

  • it serves as a hint to the compiler to perform the inlining optimization (this is basically useless on modern compilers, which inline aggressively with or without the keyword)
  • it tells the compiler/linker to ignore the One Definition Rule: that the inline'd symbol may be defined in multiple translation units (typically because it is defined in a header, that is included from multiple files). Normally, this would result in a linker error, but it is allowed when you use the inline keyword.