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?
The problem of deciding how to return a non-trivial object from some sort of a container is actually non-trivial:
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
.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.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&
.