"Erik" <er***@dsv.su.se> wrote in message
news:fa********************************@4ax.com...
string s1 = "abc";
string s2 = s1;
string is a class
string s1; // declare a variable of typle class string
internally in the string class there are the base string, some char array
and such.
now that we have s1 as a string we can work with it.
s1 = "text";
s1 is now equal to "text"
if we declare another string..
string s2;
and do like you do in your sample
s2 = s1;
In the string class there is operator= defined, and it will copy the content
of s1 into s2.
Not only the pointer, but the whole string. If it only copied the pointer to
the string object this would be a problem:
string s1,s2,s2;
s1 = "Hello",
s2 += "World!";
s3 = s1;
s3 += " ";
s3 += s2;
cout << s3 << endl;
prints "Hello World!";
string is not thread safe. Like any other class where 2 or more threads
share the same object.
If this is the case when you use the string.. you can just make you own
class derived from std::string and add a simple lock.
However i dont see the need for multiply threads to manipulate the same
string.
Anyway 2 threads can not write to same block of memory at the same time.
if you only have 1 cpu the OS will time slice between each thread and
therefore can only 1 thread write memory.
However, lets say you assign a value to a string in thread 1, while
std::string is copying and is only 50% done
the os decides that this threads timeslice ended, and now thread 2 will be
given time. If thread 2 also writes to
this same string, then you would end up with a "mixed" content.. eg. thread
1 puts "text" into the string and thread 2 puts "abcd" into it.
the result might look like "aesd". With 2 or more processors, the value in
memory cant be written by 2 processors at the same time.
However, in the example before the os would time slice, with 2 processors
the 2 threads might run simultaniously.
In that case the bytes written in memory, will have the value written from
the last cpu that flushes it memory cache
(it will overwrite whats written before by the other cpu).
however, there is no worries if many threads just read the variable and none
of them writes to it.
I hope that was understandable..
//eric