const issues and more!
Steven Schveighoffer
schveiguy at yahoo.com
Mon Jan 14 14:03:31 PST 2008
"Bill Baxter" wrote
> Walter Bright wrote:
>> Neil Vice wrote:
>>> Firstly the following simple initialiser fails to compile:
>>>
>>> char[] text = "text";
>>>
>>> As far as I can tell there is no way to declare and initialise an array
>>> in a single line of code
>>
>> string text = "text";
>
> My intuition is that an implicit dup should happen.
> Why? Well, maybe it's just familiarity with C++?
>
> std::string text = "hello"; // makes a copy
> text[0] = 'b'; // ok because we have a copy
>
> --bb
If assigning one string to another made a copy, you lose all the performance
benefits of slicing. If I make 20 "copies" of the same string, as long as
the string is invariant, there is no reason that I need to keep 20 copies of
it in memory.
That being said, let's examine the following line:
char[] text = "hello";
The compiler could interpret this 2 ways. One is "yes, compiler, I know
that "hello" is invariant, I just want a mutable copy of it", The other is
"oops, I really meant to get a read-only pointer to that string data, so
give me an error".
If the compiler interprets the first way, the coder who wants a read-only
pointer isn't warned that he now has used inefficient heap memory. If the
compiler inteprets the second way, the coder who wants a copy is told he
cannot do it that way, he fixes it, and now everyone is happy.
I like the way it works now. Err on the side of clarity and efficiency.
-Steve
More information about the Digitalmars-d
mailing list