Why D const is annoying

Timon Gehr timon.gehr at gmx.ch
Tue Dec 13 02:45:44 PST 2011


On 12/13/2011 01:58 AM, Jesse Phillips wrote:
> On Sun, 11 Dec 2011 19:40:42 +0100
> Mafi<mafi at example.org>  wrote:
>
>> void f(ref const(int)* a, const(int)* b) {a = b; }
>> void main() {
>>     immutable(int)* a;
>>     auto b = (new int[](5)).ptr;
>>     f(a, b);
>>     //if this compiles I have just assigned a mutable pointer
>>     //to an immutable one
>> }
>>
>> With the above definition using inout, such a call would be
>> disallowed.
>
> Just gave this code a try:
>
> void f(ref const(int)* a, const(int)* b) {a = b; }
> void main() {
>     const(int)* a;
>     immutable(int)* b;
>     auto c = (new int[](5)).ptr;
>     f(a, c);
>     f(b, c); //test.d(7): Error: cast(const(int)*)b is not an lvalue
> }

Interesting. That is another bug that masks the one you were trying to 
exploit. :o) Consider:

void f(const ref int* a) { }
void main() {
     immutable(int)* a;
     f(a); // same error, but should compile
}

Anyway this does the same bad stuff as your example was trying to do and 
currently compiles:

void f(const(int)** a, const(int)* b) {*a = b; }
void main() {
     const(int)* a;
     immutable(int)* b;
     auto c = (new int[](5)).ptr;
     f(&a, c);
     f(&b, c); // now goes through
}








More information about the Digitalmars-d mailing list