When do compilers inline C++ code?
Solution 1:
The inline keyword really just tells the linker (or tells the compiler to tell the linker) that multiple identical definitions of the same function are not an error. You'll need it if you want to define a function in a header, or you will get "multiple definition" errors from the linker, if the header is included in more than one compilation unit.
The rationale for choosing inline as the keyword seems to be that the only reason why one would want to define a (non-template) function in a header is so it could be inlined by the compiler. The compiler cannot inline a function call, unless it has the full definition. If the function is not defined in the header, the compiler only has the declaration and cannot inline the function even if it wanted to.
Nowadays, I've heard, it's not only the compiler that optimizes the code, but the linker can do that as well. A linker could (if they don't do it already) inline function calls even if the function wasn't defined in the same compilation unit.
And it's probably not a good idea to define functions larger than perhaps a single line in the header if at all (bad for compile time, and should the large function be inlined, it might lead to bloat and worse performance).
Solution 2:
Yes, the compiler can inline code even if it's not explicitly declared as inline
.
Basically, as long as the semantics are not changed, the compiler can virtually do anything it wants to the generated code. The standard does not force anything special on the generated code.
Solution 3:
Compilers might inline any function or might not inline it. They are allowed to use the inline
decoration as a hint for this decision, but they're also allowed to ignore it.
Also note that class member functions have an implicit inline
decoration if they are defined right in the class definition.