Should one never use static inline function?

后端 未结 5 1410
暗喜
暗喜 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:48

    Your analysis is correct, but doesn't necessarily imply uselessness. Even if most compilers do automatically inline functions (reason #1), it's best to declare inline just to describe intent.

    Disregarding interaction with inline, static functions should be used sparingly. The static modifier at namespace scope was formerly deprecated in favor of unnamed namespaces (C++03 §D.2). For some obscure reason that I can't recall it was removed from deprecation in C++11 but you should seldom need it.

    So, Practically marking a function static and inline both has no use at all. Either it should be static(not most preferred) or inline(most preferred),

    There's no notion of preference. static implies that different functions with the same signature may exist in different .cpp files (translation units). inline without static means that it's OK for different translation units to define the same function with identical definitions.

    What is preferred is to use an unnamed namespace instead of static:

    namespace {
        inline void better(); // give the function a unique name
    }
    
    static inline void worse(); // kludge the linker to allowing duplicates
    

提交回复
热议问题