Isn't C++'s inline totally optional?

后端 未结 4 1040
后悔当初
后悔当初 2020-12-08 01:24

I have a class that had an inline member, but I later decided that I wanted to remove the implementation from the headers so I moved the members body of the functions out to

4条回答
  •  醉梦人生
    2020-12-08 01:54

    Regarding harshath.jr's answer, a method need not be declared inline if its definition has the "inline" keyword, and that definition is available in the same header, i.e.:

    class foo
    {
      void bar();
    };
    
    inline void foo::bar()
    {
      ...
    }
    

    This is useful for conditionally inlining a method depending on whether or not the build is "debug" or "release" like so:

    // Header - foo.h
    
    class foo
    {
      void bar();  // Conditionally inlined.
    };
    
    #ifndef FOO_DEBUG
    # include "foo.inl"
    #endif
    

    The "inline" file could look like:

    // Inline Functions/Methods - foo.inl
    #ifndef FOO_DEBUG
    # define FOO_INLINE inline
    #else
    # define FOO_INLINE
    #endif
    
    FOO_INLINE void foo::bar()
    {
      ...
    }
    

    and the implementation could like the following:

    // Implementation file - foo.cpp
    #ifdef FOO_DEBUG
    # include "foo.inl"
    #endif
    
    ...
    

    It's not exactly pretty but it has it's uses when aggressive inline becomes a debugging headache.

提交回复
热议问题