Calls to struct methods and immutable
Joseph Rushton Wakeling
joseph.wakeling at webdrake.net
Fri Nov 16 03:55:04 PST 2012
On 11/16/2012 05:51 AM, Ali Çehreli wrote:
> 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.
Unfortunately in general that's a no-go as some of the generation functions
involve reading from outside files, and some involve random number generation
(though I'm curious to see the result of bearophile's pure RNG).
> 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);
> }
> }
I'll have a look into this. The trouble is that it's not such a simple
structure: it's actually more like,
struct Data
{
Node[size_t] nodes;
}
struct Node
{
size_t id;
size_t[];
}
... is it possible to just do
auto copy = to!(Node[size_t])(nodes);
immutable inodes = assumeUnique(copy);
or would I have to go further recursively into Node? (Or, alternatively, will
assumeUnique pick up on any idup method I define for Node?)
More information about the Digitalmars-d-learn
mailing list