peculiarities with char[] and std.string

BCS BCS at pathlink.com
Mon Jun 19 09:41:59 PDT 2006


Kyle K wrote:
> In article <e76aq8$qsr$1 at digitaldaemon.com>, xs0 says...
> 
>>Well, you didn't touch the memory you didn't allocate :) If you had
>>
>>char[] bob(in char[] str)
>>{
>>    str[0] = 'a';
>>    return str;
>>}
>>
>>You'd get "aoo:aoo" as output (or a crash, as you can't write into 
>>constants on some platforms)
> 
> 
> Ah ok, that makes sense. So using 'in' with arrays and aggregate types will
> always still give you a reference? I assume with primitives the semantics remain
> pass-by-value, such that foo(in int b) will never modify the caller's data?
> 
> 
Actually "in" always gives you a copy of the actual "thing". Arrays are 
reference types so you get a copy of the reference. Same with objects, 
as they are also reference types. Stucts on the other hand are not 
reference types and as such will get passed by value


class fooC{int i;}
struct fooS{int i;}


void main()
{
	fooC c1= new fooC, c2;
	c1.i = 0;
	c2 = fn(c1);
	writef(c1.i, " ", c2.i, \n);	// prints "1 1"

	fooS s1, s2;
	s1.i = 0;
	s2 = fn(s1);
	writef(s1.i, " ", s2.i, \n);	// prints "0 1"

}

fooC fn(in fooC v)
{
	v.i=1;
	return v;
}

fooS fn(in fooS v)
{
	v.i=1;
	return v;
}



More information about the Digitalmars-d-learn mailing list