Usefulness of the “inline” feature

前端 未结 8 1292
难免孤独
难免孤独 2020-12-06 14:40

There\'s two things about inlining:

  • The inline keyword will be ignored if the compiler determines that the function cannot be inlined.
  • Th
相关标签:
8条回答
  • 2020-12-06 15:00

    It depends on your environment and what you want to do, so it is really hard to say when inlining is preferrable.

    This link has some interesting reading about inlining. And some sound advice (which pretty much boils down to: avoid doing it)

    0 讨论(0)
  • 2020-12-06 15:07

    Yes, if you want to put a function in a header file, and include that file in several translation units. This is in fact the main purpose of inline in C++.

    0 讨论(0)
  • 2020-12-06 15:08

    The inline keyword has two functions:

    • it serves as a hint to the compiler to perform the inlining optimization (this is basically useless on modern compilers, which inline aggressively with or without the keyword)
    • it tells the compiler/linker to ignore the One Definition Rule: that the inline'd symbol may be defined in multiple translation units (typically because it is defined in a header, that is included from multiple files). Normally, this would result in a linker error, but it is allowed when you use the inline keyword.
    0 讨论(0)
  • 2020-12-06 15:10

    Read Herb Sutters comments on inline:
    http://www.gotw.ca/gotw/033.htm

    0 讨论(0)
  • 2020-12-06 15:12

    Inline is also useful if you want the ability to inline functions from a library. Only by putting the code for the function in the header file (which requires inline), is the compiler able to inline the function. Of course it is still up the the compiler whether to inline the function or not.

    0 讨论(0)
  • 2020-12-06 15:13

    There's a side effect of inline keyword when you are building shared library. Inlined functions are not exported into symbol table nor into library's binary. As a result inline keyword is crucial in aspect of shared libraries, since compiler won't be able to inline exported function. On the other hand library's inline function will be always inlined because it doesn't exist in the binary form of the library.

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