Will C++ linker automatically inline functions (without “inline” keyword, without implementation in header)?

前端 未结 8 1255
余生分开走
余生分开走 2021-02-07 06:42

Will the C++ linker automatically inline \"pass-through\" functions, which are NOT defined in the header, and NOT explicitly requested to be \"inlined\" through the

8条回答
  •  星月不相逢
    2021-02-07 07:39

    Here is my understanding of what the compiler will do with functions:

    If the function definition is inside the class definition, and assuming no scenarios which prevent "inline-ing" the function, such as recursion, exist, the function will be "inline-d".

    If the function definition is outside the class definition, the function will not be "inline-d" unless the function definition explicitly includes the inline keyword.

    Here is an excerpt from Ivor Horton's Beginning Visual C++ 2010:

    Inline Functions

    With an inline function, the compiler tries to expand the code in the body of the function in place of a call to the function. This avoids much of the overhead of calling the function and, therefore, speeds up your code.

    The compiler may not always be able to insert the code for a function inline (such as with recursive functions or functions for which you have obtained an address), but generally, it will work. It's best used for very short, simple functions, such as our Volume() in the CBox class, because such functions execute faster and inserting the body code does not significantly increase the size of the executable module.

    With function definitions outside of the class definition, the compiler treats the functions as a normal function, and a call of the function will work in the usual way; however, it's also possible to tell the compiler that, if possible, you would like the function to be considered as inline. This is done by simply placing the keyword inline at the beginning of the function header. So, for this function, the definition would be as follows:

    inline double CBox::Volume()
    {
        return l * w * h;
    }
    

提交回复
热议问题