Writing function definition in header files in C++

后端 未结 7 1533
孤城傲影
孤城傲影 2020-11-30 20:00

I have a class which has many small functions. By small functions, I mean functions that doesn\'t do any processing but just return a literal value. Something like:

7条回答
  •  悲哀的现实
    2020-11-30 20:23

    Depending on your compiler and it's settings it may do any of the following:

    • It may ignore the inline keyword (it is just a hint to the compiler, not a command) and generate stand-alone functions. It may do this if your functions exceed a compiler-dependent complexity threshold. e.g. too many nested loops.
    • It may decide than your stand-alone function is a good candidate for inline expansion.

    In many cases, the compiler is in a much better position to determine if a function should be inlined than you are, so there is no point in second-guessing it. I like to use implicit inlining when a class has many small functions only because it's convenient to have the implementation right there in the class. This doesn't work so well for larger functions.

    The other thing to keep in mind is that if you are exporting a class in a DLL/shared library (not a good idea IMHO, but people do it anyway) you need to be really careful with inline functions. If the compiler that built the DLL decides a function should be inlined you have a couple of potential problems:

    1. The compiler building the program using the DLL might decide to not inline the function so it will generate a symbol reference to a function that doesn't exist and the DLL will not load.
    2. If you update the DLL and change the inlined function, the client program will still be using the old version of that function since the function got inlined into the client code.

提交回复
热议问题