开发者

Reusing the same string before inserting to a list seems to pass by value?

开发者 https://www.devze.com 2023-01-26 11:24 出处:网络
list<string> l; string s; getline(cin, s); l.push_back(s); getline(cin, s); l.push_back(s); 开发者_Go百科
list<string> l;
string s;

getline(cin, s);
l.push_back(s);
getline(cin, s);
l.push_back(s);
开发者_Go百科

Using input

123
test

Printing the list 'l' results:

123
test

Shouldn't this print:

test
test

I'm a little confused as to why the string is being passed by value.


push_back copies the string object s passed into it. So wahetever modification you do to s is not affecting the pushed back value.


It shouldn't, because the string is copied when you add it to the list l. string argument is passed by reference to getline:

istream& getline ( istream& is, string& str );


Your title is misleading; you don't have a loop anywhere in the code that you posted.

The string is being passed by value to push_back, which makes a copy in the list. The results you're getting are exactly what I would expect.


Pseudocode:

void list::push_back(string& s)
{
   list_.add(new string(s));   // copy string
}

You see, the string is copied in push_back method. It is passed by reference just to avoid a redundant copying.

void list::push_back(string s) // copy string
{
   list_.add(new string(s));   // copy string
}
0

精彩评论

暂无评论...
验证码 换一张
取 消