peculiarities with char[] and std.string

Kyle K Kyle_member at pathlink.com
Mon Jun 19 06:38:57 PDT 2006


Greetings.

I was poking around the std.string lib, and was wondering if someone could
answer a few questions about it. I'm relatively new to D, so I'm sure there are
pretty obvious answers.

I notice in most of the functions like toStringz() and tolower() it implements
the copy-on-write convention... but since the default function parameter is in,
is there not already an implicit copy of the data being made? For example,

import std.stdio;
int main()
{
char []str, str2;
str="foo";
str2= bob(str);
writefln("%s:%s", str, str2);  // should print "foo:keke"
return 0;
}
char []bob(in char[] str)
{
str = "keke"; 
return str;
}

Works fine with my copy of DMD. Is this behavior not to be relied on as you
shouldn't ever touch memory you didnt allocate (according to the FAQ)?


Also, why is the following the case:

printf("%s", "hello\0"); // Fails with access violation
printf("%s", cast(char *)"hello\0"); // OK

Is the implicit casting from char[] to char * doing something im not aware of in
terms of the length of the string, like chopping off the \0?

My last question is which is the preferred method of making a copy of a string?
Suppose I want str2 to be a copy of str, then:

str2.length = str.length;
str2[] = str;
//      These two equivalent?
str2 = str.dup;

Sorry for all the questions and thanks for the help, let me know if this info is
somewhere obvious.. I wasn't able to find it in the spec.

Regards
Kyle K.





More information about the Digitalmars-d-learn mailing list