Why I (Still) Won't Use D
Janice Caron
caron800 at googlemail.com
Fri Mar 28 10:56:52 PDT 2008
On 28/03/2008, Sean Kelly <sean at invisibleduck.org> wrote:
> I'm sorry, but unless I missed a memo, this hasn't been the case for probably
> ten years.
In Microsoft's implementation of std::string, there is a one-byte
reference count immediately preceeding the first char. So if you do
std::string s = "hello";
then somewhere in memory (in fact, at (&s[0])-1), there will be an
array [ 1, 'h', 'e', 'l', 'l', 'o', 0 ], If you then do
std::string t = s;
then that array changes to [ 2, 'h', 'e', 'l', 'l', 'o', 0 ], but no
copy of the string data is made. If you then modify one of the strings
s[0] = 'j';
then a new array is constructed, pointers are moved about, counters
are decremented, and you end up with s having an array of [ 1, 'j',
'e', 'l', 'l', 'o', 0 ] and t having a brand new array of [ 1, 'h',
'e', 'l', 'l', 'o', 0 ].
The process stops when the reference counter reaches 254. A value of
255 is special, and means "always copy". Also, these things contain a
lock to keep them thread-safe.
I'm sure that's how it works - at least in Visual Studio 6 and 7. But
feel free to tell me if I'm wrong.
More information about the Digitalmars-d
mailing list