String mutability

Hi,

I'm new to C++ coming from a background of C#, and am trying to understand how the string class in C++ works. I've read that strings are mutable in C++, but despite this there's some behaviour that I can't quite understand such as in the following example I found online:

1
2
3
4
5
6
7
8
9
10
11
//Declaration for the string data
std::string strData = "One";
//Declaration for C++ vector
std:: vector <std::string> str_Vector;
str_Vector.push_back(strData);
strData = "Two";
str_Vector.push_back(strData);
strData = "Three";
str_Vector.push_back(strData);
strData = "Four";
str_Vector.push_back(strData);


I've verified in my IDE that the str_Vector object contains "One", "Two", "Three", "Four" as implied by the code, however I can't quite understand why.

I am wondering why str_Vector does not become "Four", "Four", "Four", "Four"? If strings are mutable in C++ and if str_Vector stores by reference (both assumptions I've made which could very well be false), then it seems to me that we just added the pointer to strData four times, and that modifying strData should also implicitly modify str_Vector.

Could someone please explain what I am missing?

Thanks


push_back copies the object in the vector so you won't have references in it
That's the problem with Java an C#. The differences between object and pointer are muddled beyond all recognition.

In C++, something doesn't point to something else if it's not declared with * or &.
For the code to behave as you expect it, it would have to look like this:
1
2
3
4
5
6
7
8
9
std::string s="One";
std::vector<std::string *> v;
v.push_back(&s);
s="Two";
v.push_back(&s);
s="Three";
v.push_back(&s);
s="Four";
v.push_back(&s);

See? Now you've pushed the same pointer into the vector four times, and changes made to any of the elements will be reflected in all the other elements. Or more accurately, changes to the object which any of the elements point to will be reflected in the object which all the other elements point to.
Ah, that makes sense! Thanks.
Topic archived. No new replies allowed.