Alex Rivera | Logout

Returning a const reference to an object instead of a copy

Asked 2008-09-25T17:33:15.037
75

Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:

class foo
{
private:
    std::string name_;
public:
    std::string name()
    {
        return name_;
    }
};

Surely the getter would be better returning a const std::string&? The current method is returning a copy which isn't as efficient. Would returning a const reference instead cause any problems?

Edit
Report

1 Answer

1

Does it matter? As soon as you use a modern optimizing compiler, functions that return by value will not involve a copy unless they are semantically required to.

See the C++ lite FAQ on this.

answered 2008-09-25T18:59:03.067

Your Answer