On Friday, 6 July 2018 at 14:11:42 UTC, Timoses wrote:
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
Aah yes I had forgotten that I had set it as auto ref. However,
even when I set that function to always return a copy of the
associative array, it didn't change anything -- the issue always
seems to be with the setter method expecting a reference.
So then, supposing it's returning a copy of the object. Given
that my setter method was still expecting a reference, is there a
reason why it doesn't even invoke the setter unless I change the
parameter from expecting a reference to expecting a copy of the
object? It's not like the function failed in any way, it just
wouldn't run the function at all. Not even while I was printing
something right at the top.