Defining a member function inside the class instead of outside in C++?

前端 未结 4 690
北海茫月
北海茫月 2021-01-24 13:23

By writing the definition of a member function inside the class in the header file as follows, I was told that compiler treats this as an inline function - hence , anywhere it e

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-24 14:00

    I was told that compiler treats this as an inline function

    Correct. That means that it's allowed to be defined in more than one translation unit, which is necessary if you want to define it in a header and include that header more than once in your program.

    Hence , anywhere it encounters this function being called in the program , it enters the complete body of the function every time instead of jumping to the one location where the function resides in memory

    No, that's not what inline means in the context of a function definition. That's the optimisation of function call inlining, which the compiler can apply to any call if it thinks it will improve the code.

    The two concepts are loosely related: compilers which process a single translation unit at a time will only be able to apply the optimisation to functions defined in the current unit, so they'll need to have multiple definitions to be able to optimise them in more than one unit.

提交回复
热议问题