Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return std::string as const reference

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?

like image 634
Aneesh Narayanan Avatar asked Nov 22 '12 07:11

Aneesh Narayanan


People also ask

How do you return a string reference in C++?

Use the std::string func() Notation to Return String From Function in C++ Return by the value is the preferred method for returning string objects from functions. Since the std::string class has the move constructor, returning even the long strings by value is efficient.

Can return type be const?

(C++) const return typeThe value of a return type that is declared const cannot be changed. This is especially useful when giving a reference to a class's internals (see example #0), but can also prevent rarer errors (see example #1). Use const whenever possible [1-7].

What is const std::string?

This is an object which points to the heap. For example, when I declare a simple std::string into the heap, my memory will look like this: As you see, a new variable is created in the stack. This simple variable contains data like the size of the content, and the pointer to the content.

What is std :: string& in C++?

C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.


2 Answers

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&.

like image 55
Dietmar Kühl Avatar answered Sep 21 '22 18:09

Dietmar Kühl


Returning by reference or const reference has no speed difference - both are very fast as they just return a reference to the original object, no copying is involved.

An object returned by (non-const) reference can be modified through that reference. In your specific example, mString is public, so it can be modified anyway (and directly). However, the usual approach with getters and setters (and the primary reason for their introduction) is encapsulation - you only allow access to your data members through the getter/setter, so that you can detect invalid values being set, respond to value changes and just generally keep the implementation details of your class hidden inside it. So getters normally return by const reference or by value.

However, if you return by const reference, it binds you to always keep an instance of std::string in your class to back up the reference. That is, even if you later want to redesign your class so that it computes the string on the fly in the getter instead of storing it internally, you can't. You'd have to change your public interface at the same time, which can break code using the class. For example, as long as you return by const-reference, this is perfectly valid code:

const std::string *result = &aSample.Get();

This code will of course produce a dangling pointer no longer compile if Get() is changed to return by value instead of const reference. (thanks to Steve Jessop for correcting me)

To sum up, the approach I would take is to make mString private. Get() can return by value or by const-reference, depending on how certain you are that you'll always have a string stored. The class would then look like this:

class sample
{
  std::string mString;

public:
  void Set(const std::string &s)
  {
    mString = s;
  }
  std::string Get() const
  {
    return mString;
  }
};
like image 23
Angew is no longer proud of SO Avatar answered Sep 21 '22 18:09

Angew is no longer proud of SO