[Issue 21856] Implicit @safe violation of immutable

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Apr 27 13:51:19 UTC 2021


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

--- Comment #2 from RazvanN <razvan.nitu1305 at gmail.com> ---
There seems to be a confusion in the compiler with regards to implicit
conversions and unique objects. If a pure functions creates a mutable object
and then it returns it, then the object is implicitly convertible to immutable
because nobody else could possibly modify.

That is why:

immutable(D) f(DA right) pure {
    D ret = right;
    return ret;
}

will compile. The compiler will consider that the function is pure, therefore
immutability cannot be broken. I think that this is a bug, since the conversion
should work only if the function is strongly pure, not any kind of purity.

But there is also the case of:

immutable(D) f(DA) pure {
    D ret = new D();
    return ret;
}

In the above case, it is fine to convert ret to immutable since nobody can
actually modify it.

The safest and most restrictive solution would be to simply allow the
conversion only if the function is strongly pure, thus dissalowing the latter
case, however, this may break code out there.

--


More information about the Digitalmars-d-bugs mailing list