Hi,
How do I properly put this to code? I am trying to return a string (name) from a function using reference.
I hope you get the idea. Thanks!Code:std::string& name()
{
cout << "Enter your name: " << endl;
getline(cin, name);
}
Printable View
Hi,
How do I properly put this to code? I am trying to return a string (name) from a function using reference.
I hope you get the idea. Thanks!Code:std::string& name()
{
cout << "Enter your name: " << endl;
getline(cin, name);
}
You need to pass in the string by reference, but you probably should either rename the function or use a different name for the string reference parameter. Of course, once you pass in the string by reference, there is not much point in returning it at all.
I think there are some cases that benefit from returning a reference. For example, I have a function to convert something to a string, and use the converted string in a string expression. I can pass in a string reference, store the converted string in it, and return a reference to it. This way, I can avoid a string copy operation. Here is some abstract code to explain what I mean:
Code:string & int2str(int i, string & str){
// convert i into str
return str;
}
int main(){
...
string tmp;
string a = "abc" + int2str(20, tmp);
...
}
Yes, but I do not think that this is one of them.Quote:
Originally Posted by plutino
Depending on your point of view, you either cannot avoid the copy (since you are initialising a new string with a temporary) or can avoid the copy either way, e.g.,Quote:
Originally Posted by plutino
Code:string tmp;
int2str(20, tmp);
string a = "abc" + tmp;
The compiler can also optimize away functions returning copies of variables, if they are not too complicated.
But you cannot return a reference to a local variable!