In my implementation files (.cc files), I often find that it’s convenient to define member functions in class definitions (such as the functions of a Pimpl class). For example:
struct X::Impl {
void DoSomething() {
...
}
};
instead of
struct X::Impl {
void DoSomething();
};
void X::Impl::DoSomething() {
...
}
I think this is preferable to implementing the function outside of the class definition for several reasons. It enhances readability and facilitates the practice of keeping methods small (by making it easy to add them). The code is also easier to maintain since you never have to update method declarations.
The only downside I see is that methods defined in the class declaration are implicitly inlined, which is not usually desirable because of the increase in the size of the object code.
My questions are:
-
Do I have this right? Are there other downsides to this practice that I’m missing?
-
Is the implicit inlining something to worry about? Is the compiler smart enough to reject my implicit request to inline methods that shouldn’t be inlined?
-
Is it possible (via compiler extensions or otherwise) to declare that a method defined in the class definition not be inlined?
The simple answer is that you should not care. Member functions defined within the class definition are implicitly
inline, but that does not mean that they are inlined (i.e. the code need not be inlined at the place of call).Compiler implementors have dedicated quite a bit of time and resources to come up with heuristics that determine whether actual inlining should be done or not, based on the size of the function, the complexity and whether it can be inlined at all or not (a recursive function cannot be inlined[*]). The compiler has more information on the generated code and the architecture in which it will run than most of us have. Trust it, then if you feel that there might be an issue, profile, and if profiling indicates that you should change the code, do it, but make an informed decision after the fact.
If you want to verify whether the function has actually be inlined or not, you can look at the assembly and check whether there are calls to the function or the code was really inlined.
[*] If the compiler can transform the recursion into iteration, as is the case in tail recursion, then the transformed function could be theoretically be inlined. But then, functions with loops have lesser probabilities of being inlined anyway…