Should one never use static inline function?

后端 未结 5 1427
暗喜
暗喜 2020-12-07 08:10

There are two implications of using the inline keyword(§ 7.1.3/4):

  1. It hints the compiler that substitution of function body at the point
5条回答
  •  醉酒成梦
    2020-12-07 08:57

    If you talk about free functions (namespace scope), then your assumption is correct. static inline functions indeed don't have much value. So static inline is simply a static function, which automatically satisfies ODR and inline is redundant for ODR purpose.

    However when we talk about member methods (class scope), the static inline function does have the value.
    Once you declare a class method as inline, it's full body has to be visible to all translation units which includes that class.

    Remember that static keyword has a different meaning when it comes for a class.
    Edit: As you may know that static function inside a class doesn't have internal linkage, in other words a class cannot have different copies of its static method depending on the translation (.cpp) units.
    But a free static function at namespace/global scope does have different copies per every translation unit.

    e.g.

    // file.h
    static void foo () {}
    struct A {
      static void foo () {}
    };
    
    // file1.cpp
    #include"file.h"
    void x1 ()
    {
      foo();  // different function exclusive to file1.cpp
      A::foo();  // same function
    }
    
    // file2.cpp
    #include"file.h"
    void x2 ()
    {
      foo();  // different function exclusive to file2.cpp
      A::foo();  // same function
    }
    

提交回复
热议问题