What Does It Mean For a C++ Function To Be Inline?

后端 未结 9 743
攒了一身酷
攒了一身酷 2020-12-01 06:12

See title: what does it mean for a C++ function to be inline?

相关标签:
9条回答
  • 2020-12-01 07:10

    @OldMan

    The compilers only inline non marked as inline functions ONLY if you request it to do so.

    Only if by "request" you mean "turn on optimizations".

    Its correct only on the effcts nto the casuse.

    It's correct in both.

    Inline do not generate any extra info that the linker may use. Compiel 2 object files and check. It allow multiple definitions exaclty because the symbols are not exported! Not because that is its goal!

    What do you mean, "the symbols are not exported"? inline functions are not static. Their names are visible; they have external linkage. To quote from the C++ Standard:

    void h(); inline void h(); // external linkage

    inline void l(); void l(); // external linkage

    The multiple definitions thing is very much the goal. It's mandatory:

    An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case (3.2). [Note: a call to the inline function may be encountered before its definition appears in the translation unit. ] If a function with external linkage is declared inline in one translation unit, it shall be declared inline in all translation units in which it appears; no diagnostic is required. An inline function with external linkage shall have the same address in all translation units.

    0 讨论(0)
  • 2020-12-01 07:11

    Calling a function imposes a certain performance penalty for the CPU over just having a linear stream of instructions. The CPU's registers have to be written to another location, etc. Obviously the benefits of having functions usually outweigh the performance penalty. But, where performance will be an issue, for example the fabled 'inner loop' function or some other bottleneck, the compiler can insert the machine code for the function into the main stream of execution instead of going through the CPU's tax for calling a function.

    0 讨论(0)
  • 2020-12-01 07:19

    Informally, it means that compilers are allowed to graft the contents of the function onto the call site, so that there is no function call. If your function has big control statements (e.g., if, switch, etc.), and the conditions can be evaluated at compile time at the call site (e.g., constant values used at call site), then your code ends up much smaller (the unused branches are dropped off).

    More formally, inline functions have different linkage too. I'll let C++ experts talk about that aspect.

    0 讨论(0)
提交回复
热议问题