inline function members inside a class

前端 未结 3 1791
悲&欢浪女
悲&欢浪女 2020-12-23 09:24

I know that declaring a function (normal function not a method inside a class) as inline is a good practice when the function definition is small for performance and it save

3条回答
  •  感情败类
    2020-12-23 09:48

    but how about inline methods inside a class ?

    Both syntaxes for inlining functions (using explicit inline and defining member-function inside class definition) provides only hint about inlining for compiler. From performance point of view, they are equal.

    In case of defining a member-function inside a class declaration, the readability of the latter should be of your main concern: it really hurts to litter class interface with multiple line of implementation details. So avoid doing that if your member-function is more than one statement: return stuff or simple forwarding should be OK, but usually no more than that.

    class MyClass
    {
    public:
        int f() const { return m_i; }
        int g() const;
    
    private:
        int m_i;
    };
    
    inline int MyClass::g() const
    {
        return m_i;
    }
    
    // both member-functions behave equally (except for naming)
    

提交回复
热议问题