www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 18563] New: context pointer inside structs constness problems

https://issues.dlang.org/show_bug.cgi?id=18563

          Issue ID: 18563
           Summary: context pointer inside structs constness problems
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: shachar weka.io

The following program does not compile:
void main() {
    struct S {
        uint value;

        ~this() {
        }
    }

    const S a = S(12);
    S b = a;
}

test.d(10): Error: cannot implicitly convert expression a of type const(S) to S 

The reason is that the context pointer stored in a is const, and thus implies
that the context it points to is also const. This cannot be copied to the
non-const context pointer in b.

This context pointer is not, however, actually treated as const. The following
code compiles and passes:

unittest {
    int i = 0;
    struct S {
        int n;
        void fun() const {
            i++;
        }
    }
    const S s;
    assert(i == 0);
    s.fun();
    assert(i == 1);
} 

Full discussion thread at
https://forum.dlang.org/thread/p7lp2b$1jod$1 digitalmars.com

I would argue that the correct solution is to allow the assignment.

--
Mar 06 2018