Return a const reference or a copy in a getter function?

cairol picture cairol · Feb 2, 2010 · Viewed 26.4k times · Source

What's better as default, to return a copy (1) or a reference (2) from a getter function?

class foo {
public:
    std::string str () { // (1)
        return str_;
    }

    const std::string& str () { // (2)
        return str_;
    }

private:
    std::string str_;
};

I know 2) could be faster but don't have to due to (N)RVO. 1) is safer concerning dangling references but the object will probably outlife or the reference is never stored.

What's your default when you write a class and don't know (yet) whether performance and lifetime issues matter?

Additional question: Does the game change when the member is not a plain string but rather a vector?

Answer

Aryabhatta picture Aryabhatta · Feb 2, 2010

Well it really depends on what you expect the behaviour to be, by default.

Do you expect the caller to see changes made to str_ unbeknownst(what a word!) to them? Then you need to pass back a reference. Might be good if you can have a refcounted data member and return that.

If you expect the caller to get a copy, do 1).