const issues and more!

Matti Niemenmaa see_signature at for.real.address
Mon Jan 14 04:21:23 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.

I'm only proficient in 1.0 and thus not very up-to-date with the current const 
situation, but I'll answer what I do (think I) know.

> 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 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";

How about:

char[] text = "text".dup;

.dup creates a mutable copy. There's also .idup, for an immutable copy, but I 
don't know its semantics.

<snip>
> It would appear that constness can be implicitly cast away through the use 
> of a foreach loop as in the following:
> 
>     const char[] test;
>     foreach(char c; test)
>     {
>         c = 'x';
>     }
> 
> Note that c is not even declared ref.

I guess this is the same thing as doing the following:

const int y;
foo(y);

void foo(int n) {
	n = n+1;
}

I.e. since you don't have ref, it's just a copy of the value which is modified. 
You'll note that the original test array is unmodified even if it's not const:

char[] foo = "foo";
foreach (c; foo)
	c = 'x';
assert (foo == "foo"); // passes

> DMD crashes when a method is called which takes a "ref const" parameter 
> e.g.:
> 
>     void test(ref const char c) { }
>     void main()
>     {
>         char c;
>         test(c);
>     }
> 
> This of course begs the question: what exactly is a ref const?

If DMD crashes and this isn't in the Bugzilla, file the bug.

If 'ref const' does work it's probably one or the other. DMD has a habit of 
accepting contradictory attributes:

public private protected int x; // quiz: what is the protection level of x?

<snip>
> Reassurances that my dreams of D being a great programming language have not 
> been shattered are welcome =) 

Use 1.0 and live happily, waiting for the const stuff to be finalized. ;-)

-- 
E-mail address: matti.niemenmaa+news, domain is iki (DOT) fi



More information about the Digitalmars-d mailing list