Re: STL string and assignment operator. Plz Help.
"developer28" <aman.k.sethi@gmail.com> wrote in message
news:1191238835.600028.12920@n39g2000hsh.googlegroups.com...
Hi,
I would like to know the following.
suppose i write.
string str1 = "TestString";
string str2;
str2 = str1
Now can someone tell me how this assignment operator works internally.
Internally most likely the bytes that represent the string in str1 are
copied into str2 byte for byte.
actually i do something like
const char * temp = str1.c_str();
Here you are not using std::strings copy constructor, you are using a const
char* copy constructor. The only thing that is copied is the value of the
pointer that c_str() returns.
that converts it to a c type string.
No, that returns a pointer to a c-style string which is still internal to
str1
and then when i modify the contents of temp, it also affects str2.
And this is not allowed, This will provoke undefined behavior. First off,
it's a const char*, constant, you are not allowed to change the contents.
Second, it is a temporary pointer, as soon as str1 changes for whatever
reason that pointer can become invalidated. Now, being undefined behavior
it can pretty much do anything, including change the original string. Or
change str2. Or str99283. It is undefined behavior. Don't do it.
Now this makes me doubtful about the fact that internally both the
objects are using the same pointer.
Both of which objects? str1 and str2? They should be using their own
pointers to their own sets of data.
Please forgive me if my query is too trivial.