Using reference before function name

Feb 14, 2017 at 8:27pm
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
element (presumably a string) is being returned by reference rather than by value.
Feb 14, 2017 at 9:57pm
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
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
It's just for performance reasons. If you don't return a reference the string would get copied.
Topic archived. No new replies allowed.