mutable, const, immutable guidelines
Daniel Davidson
nospam at spam.com
Thu Oct 10 16:26:57 PDT 2013
On Thursday, 10 October 2013 at 23:06:23 UTC, qznc wrote:
> Maybe the fact that D allows this implicit copy to immutable is
> the problem? If one could require the use of a specific
> function, this function could be overridden with working
> behavior. The following code works.
>
Yes - the issue arises because the language has different
behavior for structs with mutable aliasing and structs without.
For structs without mutable aliasing a copy is safe so crossing
bounds between any of (mutable, const, immutable) is easily
achieved.
> import std.exception: assumeUnique;
>
> struct MyInt
> {
> int i;
> private int[] history; // <-- Added
> }
>
> // idup for creating immutable MyInts
> immutable(MyInt) idup(const MyInt mi) pure nothrow @trusted {
> MyInt cpy = MyInt(mi.i);
> return cast(immutable) cpy;
> }
>
> // special version for performance
> immutable(MyInt) idup(immutable MyInt mi) pure nothrow @trusted
> {
> return mi;
> }
>
> unittest {
> auto a = MyInt(1);
> immutable b = a.idup; // <-- Code does not break
> }
>
> D could either remove the implicit-copy-to-immutable or provide
> a special copy-constructor for immutable structs.
See this discussion:
http://forum.dlang.org/thread/fmhkvogowjlduqercsjn@forum.dlang.org
More information about the Digitalmars-d-learn
mailing list