[Issue 2093] string concatenation modifies original

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Nov 21 22:39:27 PST 2008


http://d.puremagic.com/issues/show_bug.cgi?id=2093





------- Comment #4 from 2korden at gmail.com  2008-11-22 00:39 -------
This is a known bug and is a major array design flow. Arrays has no determined
owner (the only one who can grow without a reallocation if capacity permits):

import std.stdio;

void main()
{
    char[] s1, s2;
    s1.length = 100; // reserve the capacity
    s1.length = 0;

    s2 = s1; // both are pointing to an empty string with the capacity of 100

    s1 ~= "Hello"; // array is not reallocated, it is grown in-place
    writefln(s1);
    writefln(s2); // prints empty string. s2 still points to the same string
(which is now "Hello") and carries length of 0

    s2 ~= "Hi"; // overwrites s1
    writefln(s2); // "Hi"
    writefln(s1); // "Hillo"
}

s1 is the array owner and s2 is a slice (even though it really points to the
entire array), i.e. it should reallocate and take the ownership of the
reallocated array on append, but it doesn't happen.

Currently an 'owner' is anyone who has a pointer to array's beginning:

char[] s = "hello".dup;
char[] s1 = s[0..4];
s1 ~= "!";
assert(s != s1); // fails, both are "hell!", s is overwritten

s = "_hello".dup;
char[] s2 = s[1..5];
s2 ~= "!";
assert(s != s1); // succeeds, s1 is not changed


-- 



More information about the Digitalmars-d-bugs mailing list