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