Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Inline methods for performance

I was told long ago to make short functions/methods that are called often inline, by using the keyword inline and writing the body in the header file. This was to optimize the code so there would be no overhead for the actual function call.

How does it look with that today? Does modern compilers (Visual Studio 2010's in this case) inline such short functions automatically or is it still "necessary" to do so yourself?

like image 647
EClaesson Avatar asked Sep 13 '12 20:09

EClaesson


1 Answers

inline has always been a hint to the compiler, and these days compilers for the most part make their own decisions in this regard (see register).

In order to expand a function inline, the compiler has to have seen the definition of that function. For functions that are defined and used in only one translation unit, that's no problem: put the definition somewhere before it's used, and the compiler will decide whether to inline the function.

For functions that are used in more than one translation unit, in order for the compiler to see the definition of the function, the definition has to go in a header file. When you do that, you need to mark the function inline to tell the compiler and linker that it's okay that there's more than one definition of that function. (well, I suppose you could make the function static, but then you could end up wasting space with multiple copies)

like image 83
Pete Becker Avatar answered Oct 21 '22 04:10

Pete Becker