Return std::string as const reference

Aneesh Narayanan picture Aneesh Narayanan · Nov 22, 2012 · Viewed 34.9k times · Source

I have a doubt on returning std::string as const reference.

class sample
{
public:
  std::string mString;
  void Set(const std::string& s)
  {
    mString = s;
  }
  std::string Get()
  {
    return mString;
  }
 };

In the Set function I am passing the std::string as const reference, const because its value is not changing inside the function.

And In Get function, actually I am confused here. Return std::string as value makes more sense. But I am not sure that, by passing the string as const reference makes any advantages. By returing string as reference will increase the exectuion speed, I think So, but I am not sure. But returning it as 'const makes any benefit for this?

Answer

Dietmar Kühl picture Dietmar Kühl · Nov 22, 2012

The problem of deciding how to return a non-trivial object from some sort of a container is actually non-trivial:

  • If the class from which you return your value imposes any sort of constraint on the object, you can't return a non-const reference because it would loose the possibility to enforce its invariants. Clearly, returning an object by non-const reference is only viable if object the member function is called on is also non-const.
  • Exposing a const reference to an object would avoid the problem with the invariants but still implies that an object of the corresponding type is actually kept internally as an implementation detail.
  • Returning an object by value may incur a significant cost for copying the object.

If you class is further a viable monitor you definitely want to return the object by value because otherwise the object can be mutated before the caller had any chance to copy it.

Basically, none of the choices is ideal. When in doubt, I return by value unless the object is known to be expensive to copy in which case I might return by const&.