const issues and more!

Neil Vice psgdg at swiftdsl.com.au
Mon Jan 14 02:10:43 PST 2008


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

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

Given this, is it possible to declare a const string? toString() cannot even 
be called on a const variable!

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.

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?

Also, the reason I discovered all of this is that I was attempting to 
implement a collection type. I defined a regular opApply method which worked 
fine on non-const instances. Declaring opApply to be a const method allows 
it to curiously work for both const and non-const instances in order to gain 
access to const and non-const members of the collection as described above.

I've struggled to correctly implement a const opApply at all, and when 
opApply is overloaded to have a const and a non-const definition, it is then 
impossible to use the foreach syntax that detects the member type for you.

All-in-all, attempting to write a collection class that works (specifically 
foreach/opApply) for both const and non-const instances has been 
frustratingly awkward if not impossible with DMD 2.009.

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





More information about the Digitalmars-d mailing list