typeid() after const/immutable qualifiers

Andrej Mitrovic andrej.mitrovich at gmail.com
Thu Aug 19 09:19:41 PDT 2010


In TDPL, page 289 & 299, there's this code (I've modified the names slightly) and explanation:

struct A
{
    const(int[]) c;
    immutable(int[]) i;
}

import std.stdio;

unittest
{
    const(A) const_a;
    immutable(A) immu_b;
}

A short version of the explanation: 

"if qualifiers would apply blindly, the types would be:

const_a.c == const(const(int[]))
const_a.i == const(immutable(int[]))

immu_b.c == immutable(const(int[])).
immu_b.i == immutable(immutable(int[])).

When two qualifiers are identical, they are collapsed into one, otherwise const(immutable(T)) and immutable(const(T)) are both collapsed into immutable(T)"

>From my interpretation, that would mean the types are now:

const_a.c == const(int[])
const_a.i == immutable(int[])

immu_b.c == immutable(int[])
immu_b.i == immutable(int[])

Am I correct so far?

Well first of all, DMD doesn't actually print it out simple qualifiers when arrays are used, for example:

const(int[]) x;
writeln(typeid(x));

Writes: 
const(const(int)[])

Which is fine, both x and it's contents are const so it's the correct output. 

The second thing which I'm actually puzzled by, is why I'm getting typeid() return the same qualifiers as defined in the struct. Here's some simplified code with using basic types, not arrays:

struct A
{
    const(int) c;
    immutable(int) i;
}

import std.stdio;

unittest
{
    const(A) const_a;
    immutable(A) immu_b;
    
    writeln("const_a.c == ", typeid(const_a.c));
    writeln("const_a.i == ", typeid(const_a.i));
    
    writeln("immu_b.c == ", typeid(immu_b.c));
    writeln("immu_b.i == ", typeid(immu_b.i));
}

void main()
{

}

Writes:
const_a.c == const(int)
const_a.i == immutable(int)

immu_b.c == const(int)
immu_b.i == immutable(int)

Shouldn't this be this instead:
const_a.c == const(int)
const_a.i == immutable(int)

immu_b.c == immutable(int)  // immu_b.c is now immutable
immu_b.i == immutable(int)

AFAIK immutable propagates to all fields of the struct, so const c should be an immutable now?


More information about the Digitalmars-d-learn mailing list