const issues and more!
Steven Schveighoffer
schveiguy at yahoo.com
Mon Jan 14 09:30:31 PST 2008
"Neil Vice" wrote
> I've been experimenting with const et. al. in 2.009 and have encountered
> some snags which I'll log here. It is quite likely that some of these
> issues are unrelated to the recent const changes or are things I have
> misunderstood and I will appreciate any feedback.
>
> Firstly the following simple initialiser fails to compile:
>
> char[] text = "text";
This is because a string literal is typed as an invariant(char)[].
const(char)[] text = "text";
or
invariant(char)[] text = "text";
or (with phobos)
string text = "text";
should all work.
>
> As far as I can tell there is no way to declare and initialise an array in
> a single line of code or even copy an array in a single line once
> declared. The only way I'm aware of to copy an array is as follows:
>
> char[] text;
> text.length = "text".length;
> text[] = "text";
Yeah, as Matti said, you want "text".dup. There is a good reason for this.
A string is an array, which is nothing but a pointer and length. If you
allow the line:
char[] text = "text";
to compile, then you are free to modify the constant "text"! For example,
in D 1.0 this works:
char[] text = "text";
text[0] = 'n';
char[] text2 = "text";
assert(text2 == "next");
These kinds of errors are subtle and hard to find. This is why you are not
allowed to have a non-const or invariant pointer to invariant data such as
string literals.
-Steve
More information about the Digitalmars-d
mailing list