Should one never use static inline function?

后端 未结 5 1425
暗喜
暗喜 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 09:04

    Static and inline are orthogonal (independent). Static means the function should not be visible outside of the translation unit, inline is a hint to the compiler the programmer would like to have this function inlined. Those two are not related.

    Using static inline makes sense when the inlined function is not used outside of the translation unit. By using it you can prevent a situation of accidental violation of ODR rule by naming another inlined function in another tranlation unit with the same name.

    Example:

    source1.cpp:

    inline int Foo()
    {
      return 1;
    }
    
    int Bar1()
    {
      return Foo();
    }
    

    source2.cpp:

    inline int Foo()
    {
      return 2;
    }
    
    int Bar2()
    {
      return Foo();
    }
    

    Without using static on Foo (or without using an anonymous namespace, which is preferred way by most C++ programmers), this example violates ODR and the results are undefined. You can test with Visual Studio the result of Bar1/Bar2 will depend on compiler settings - in Debug configuration both Bar1 and Bar2 will return the same value (inlining not used, one implementation selected randomly by the linker), in Release configuration each of them will return the intended value.

提交回复
热议问题