Feb 14, 2017 at 8:27pm UTC
Can someone explain what this does:
const string &foo() const
{
return element;
}
I understand why we use references before variable names, or in parameters, but in functions whats the usage?
Feb 14, 2017 at 8:31pm UTC
element (presumably a string) is being returned by reference rather than by value.
Feb 14, 2017 at 9:57pm UTC
const string &foo() const
could also have been written const string& foo() const
, which at least to me more clearly shows that the return type of the function is a reference to const string .
Feb 14, 2017 at 10:24pm UTC
I understand that it's returning a reference to a string, however if I remove the reference, I still return the same thing.
Can someone give me a practical example of why you would return by reference?
Feb 14, 2017 at 10:41pm UTC
It's just for performance reasons. If you don't return a reference the string would get copied.