Qualified destructors / immutable objects
via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jun 14 03:33:56 PDT 2015
On Sunday, 14 June 2015 at 07:28:39 UTC, anonymous wrote:
> To come back to destructors and immutable objects:
>
> Even without the default initialized variables issue it is
> possible to modify immutable data:
>
> struct S {
> int[] bar;
>
> ~this() {
> bar[0] = 123;
> }
> }
>
> void foo(immutable(int[]) i) {
> immutable(S) s = immutable S(i);
> }
>
> void main() {
> immutable array = [42, 42];
> foo(array);
> // fails
> assert(array == [42, 42]);
> }
>
> I'm not sure whether ~this() should be forbidden to modify
> immutable data. Consider e.g. some fields need to be free'd. If
> someone else is using references to such a field after ~this()
> -> segfault, but it could be seen as analogon to the list of
> undefined operations on pointer to GC memory.
> Additionally the same happens already for stack allocated
> fields like int[4] inside a (mutable/const/immutable) struct.
Found this bug report [1], in which Andrei says: "Mutable
destructors shouldn't apply to objects that were immutable,
otherwise they can mutate immutable objects."
[1] https://issues.dlang.org/show_bug.cgi?id=4338#c6
More information about the Digitalmars-d-learn
mailing list