Passing a reference to a returned reference
Timoses
timosesu at gmail.com
Fri Jul 6 14:11:42 UTC 2018
On Friday, 6 July 2018 at 13:13:43 UTC, Michael wrote:
> static auto ref consensus( ... )
`auto ref` infers the return type from the return statement [1].
So it's not necessarily returning a ref type.
However, I don't think this matters if the only concern you have
is that the setter function actually modifies the passed object.
>
> and the agent's setter method looks like the following:
>
> void beliefs(ref double[int] beliefs)
>
> Now obviously if I remove ref in the above signature,
> everything works fine, but I am surprised I wasn't getting any
> kind of warning about the reference because the setter function
> just doesn't run at all. I tried checking if (beliefs is null)
> but perhaps this isn't the correct way to check if an
> associative array's reference is no longer reachable?
>
> Some explanation would be great, thanks!
This works for me:
auto create()
{
string[int] dict;
dict[2] = "hello";
return dict;
}
void modifyNoRef(string[int] m)
{
writeln("Address not ref: ", &m);
m[0] = "modified";
}
void modifyRef(ref string[int] m)
{
writeln("Address ref: ", &m);
m[1] = "modified";
}
unittest
{
auto r = create();
writeln("Address r: ", &r);
assert(r.keys.length == 1);
modifyNoRef(r);
assert(r.keys.length == 2);
modifyRef(r);
assert(r.keys.length == 3);
}
So either with ref or not as parameter storage class the assoc.
array is modified. Note the address in the "ref" one is the same
as "r" in the unittest.
[1]: https://dlang.org/spec/function.html#auto-ref-functions
More information about the Digitalmars-d-learn
mailing list