static vs inline for functions implemented in header files

后端 未结 4 1138
心在旅途
心在旅途 2021-02-01 18:20

The way I think of inline in C++ is for linkage/scoping. I put it in the same basket with extern and static for global objects.

Ty

相关标签:
4条回答
  • 2021-02-01 18:53

    In many cases you will not notice a difference because compilers and linkers are pretty smart these days. However, an inline function must behave as-if it was a regular function. A static function in a header will get compiled into every source file which includes it - so there will be lots of copies of it.

    Mostly, this doesn't matter much, but there are a few ways it does. An inline function has one address. Static functions will have a different address in each translation unit.

    Static-local variables: WIth the inline, there will be a single copy of them. With static-functions, there will be a unique copy of each static-local variable for each translation unit that includes that function.

    0 讨论(0)
  • 2021-02-01 19:00

    inline conveys exactly what you want: "please suppress the ODR (One Definition Rule) for this function, so that each translation unit can (and must) supply its own copy of the function's definition".

    The compiler will then either inline calls to the function, or merge together the function definitions from different TU's (so that the resulting function exists once in the executable).

    static, on the other hand, tells the compiler to generate the function in every translation unit where it is defined, and just not share it. So you end up with an arbitrary number of technically separate functions existing in the resulting executable.

    In a nutshell, if you use static, then taking the address of the function in different translation units will return different addresses (because you're telling the compiler to generate a function in each TU), but if you use inline, they'll show the same address (because you're defining one function, and just telling the compiler to merge the many definitions together).

    0 讨论(0)
  • 2021-02-01 19:06

    No one seems to be mentioning that in C++, a static function is one that is called directly, not on an instance of the class. In other words, there is no implicit "this" pointer. If function foo of class MyClass is static, you say:

    MyClass::foo(); // calls it

    and not: MyClass an_object = new MyClass(); an_object->foo();

    0 讨论(0)
  • 2021-02-01 19:12

    The main difference is what happens with any static locals in the function -- if the function is static then each compilation unit will have its own copy of the static locals distinct from any other compilation unit. If the function is inline, there will only be one (set of) static local(s) shared by all compilation units.

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