Best practice for hosting inline functions in C ++

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

  • In the class definition header file
  • At the end of the header file
  • In the source file (in this case, use the keyword inline or extern inline ?)
+4
source share
4 answers

You cannot enter built-in functions in the source file (and use them as built-in functions) because their definition will not be available at the points that they need the compiler to embed the code.

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

+8
source

In the class definition header file

usually if your build time is more important (assuming this is not the case, based on the question). the exception follows

At the end of the header file

rarely. I deal with nasty patterns just to clean things up. the body is usually so small that it does not distract, and this can lead to implementation details (as a substitute for documentation, but I believe that some people will force me to do so). Example:

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

In some cases, this approach may be good hygiene. I actually used secondary files for this (fourth option).

In source file

this option is ideal - if it appears in every translation where you name it. otherwise send it back to the header.

In this case, should you use the keyword inline or extern inline?

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

+1
source

My personal preference is to place it in the header file:

 class A { private: int a; public: const int getA() const { return a; } void setA(int val) { a = val; } }; 

Just because the getX, setX functions are so small that they can easily fit on one line.

In general, my get and set methods are usually one line (only in some cases did they require actual non-trivial code).

If you have non-trivial code there, for example, checking borders or some additional calculations, I would advise you not to insert it in the header file.

0
source

Where do your coding instructions say to put them. There is no absolute rule, but in general:

- it is better to avoid built-in functions until the profiler says they need you, and many programming recommendations prohibit them, and

- It is usually best to avoid as much as possible in the class definition that is not related to the actual interface; most Coding Guides involve embedding at the end of the header, or even in a separate file included in the header.

Having said that, if the function is so simple that it comes at the end of the line with the function declaration, I donโ€™t think it really hurts.

0
source

Source: https://habr.com/ru/post/1344545/


All Articles