Implications of using an ampersand before a function name in C++?

后端 未结 5 1608
Happy的楠姐
Happy的楠姐 2020-12-17 17:38

Given the example:

inline string &GetLabel( ) {
        return m_Label;
};

Where m_Label is a private class member variable.

5条回答
  •  时光说笑
    2020-12-17 18:45

    The ampersand isn't before the function name so much as it's after the return type. it returns a reference to a string.

    The implication of this is that a caller of this function could modify the value of m_label through the reference. On the other hand, it avoids copying the string. You might want the reference and the function to be const, like so:

    inline const string& GetLabel() const
    {
        return m_Label;
    }
    

    Best of both worlds. You avoid the copy, but callers can't change your object.

提交回复
热议问题