I'm totally new to the const/immutable thing, so this might be a naive question..

The spec says:
"modification after casting away const" => "undefined behavior"

// ptr to const int
const(int)* p;
int* q = cast(int*)p;
*q = 3;   // undefined behavior

But why would you want to cast away const then? If it's for passing to a function that doesn't take const, you're just shooting yourself in the foot by giving it illegal data to work with.

This little test works:
unittest
{
        const int i = 10;
        const(int)* p = &i;
        assert(*p == 10);
        assert(p == &i);
        
        int* q = cast(int*)p;
        assert(q == &i);
        assert(*q == 10);
        
        *q = 1; // spec says undefined behavior
        assert(*q == 1); // but the value is changed
        assert(*p == 1); // but p is also changed
        
        assert(p == q); // still same reference.
        assert(q == &i);
        assert(p == &i);
        assert(i == 10); // i still 10 though.. How is this possible?
}

Reply via email to