Calls to struct methods and immutable

Ali Çehreli acehreli at yahoo.com
Thu Nov 15 20:51:16 PST 2012


On 11/15/2012 07:43 PM, Kenji Hara wrote:

 > This code works with dmd git head (and might work with dmd 2.060).

Yes, it works with dmd 2.060 as well.

 > immutable(Foo) makeFoo() pure

I would like to repeate an earlier question: Does makeFoo() want that 
the returned object be immutable? If so, the previous signature is required.

However, if makeFoo() does not care, then it would be better if it 
returned a mutable Foo:

Foo makeFoo() pure

In that case the callers could decide whether they wanted to have the 
returned object as mutable or immutable:

     immutable ifoo = makeFoo();
     auto mfoo = makeFoo();

The above works because makeFoo() is pure.

If makeFoo() were not pure, and in general, Foo may need to provide an 
.idup member function:

import std.conv;
import std.exception;

struct Foo
{
     int a, b;
     string[string] aa;
     int[] slice;

     immutable(Foo) idup() pure const @property
     {
         auto copy = to!(string[string])(aa);
         immutable iaa = assumeUnique(copy);
         return immutable(Foo)(a, b, iaa, slice.idup);
     }
}

void main()
{
     auto foo = Foo(42, 43, [ "a" : "hello", "b" : "world" ], [ 42 ]);
     immutable ifoo = foo.idup;
}

Ali



More information about the Digitalmars-d-learn mailing list