Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for the placement of inline functions in C++

Tags:

c++

Which is better for short functions (e.g. getters and setters)

  1. In the class definition header file
  2. At the end of the header file
  3. In the source file (in this case should I use the inline keyword or extern inline?)
like image 646
brian14708 Avatar asked Jan 20 '23 04:01

brian14708


2 Answers

You can't put inline functions in the source file (and have them used as inline) because their definition won't be available at the points the compiler needs them to inline the code.

Between the other two options, I tend to put one liners into the class definition and any others at the end of the header.

like image 70
Mark B Avatar answered Jan 22 '23 20:01

Mark B


In the class definition header file

typically, unless your build times are more important (assuming that's not the case, based on the question). an exception follows

At the end of the header file

rarely. i have when dealing with nasty templates, just to clean things up. the body is usually so small that it is not distracting, and this can expose implementation details (as a substitute for documentation, but i figure some people will rail me for that). example:

void compute() {
  assert(this->hasEnoughEnergyToCompute());
  ...computing
}

this approach can be good hygiene in some cases. i've actually used secondary files for this (a fourth option).

In the source file

this option is ideal - if it's visible in every translation where you call it. otherwise, send it back to the header.

in this case should I use the inline keyword or extern inline?

just 'inline'. in fact, your compiler probably declares methods inline implicitly. omit it altogether if all your required compilers support this.

like image 26
justin Avatar answered Jan 22 '23 18:01

justin