passing strings to functions

When passing a string from std::string into a function, do you have to reference the address?

Which is correct:

1
2
3
4
string foo(string my_string)
{
return my_string
}


or
1
2
3
4
string& foo(string& my_string)
{
return my_string&
}
Last edited on
Passing without the & makes a copy of the variable. Passing with the & passes the address of the variable.


In your second example you do not need the & when you return it. The declaration of string& already tells the compiler that you are returning a reference.

Just make sure that if you return a reference that it is not a reference to a variable that was declared inside that function or you will be returning a ghost reference since when the function finishes executing that variable is destroyed. (unless its static)

Topic archived. No new replies allowed.