Taking arguments by value or by reference
geod24 at gmail.com
Sun Oct 4 16:37:51 UTC 2020
On Sunday, 4 October 2020 at 14:26:43 UTC, Anonymouse wrote:
> I mostly really only want a read-only view of the struct, and
> whether a copy was done or not is academic. However, profiling
> showed (what I interpret as) a lot of copying being done in
> release builds specifically.
> Naturally a situation where I need ref I'd use ref, and in the
> rare cases where it actually helps to have a mutable copy
> directly I take it mutable. But if I understand what you're
> saying, and ignoring --preview=in, you'd recommend I use const
> ref where I would otherwise use const?
> Is there some criteria I can go by when making this decision,
> or does it always reduce to looking at the disassembly?
If the struct adds overhead to copy, use `const ref`. But if you
do, you might end up with another set of problems. Aliasing is
one of them, and the dangers of it are discussed at length in the
thread about `-preview=in` in general. The other issue is that
`const ref` means you cannot pass rvalues.
This is when people usually turn towards `auto ref`.
Unfortunately, it requires you to use templates, which is not
So, in short: `auto ref const` if it's a template and aliasing is
not a concern, `const ref` if the copy adds overhead, and add a
`const` non-`ref` overload to deal with rvalues if needed. If you
want to be a bit more strict, throwing `scope` in the mix is good
Now, about `-preview=in`: The aim of this switch is to address
*exactly* this use case. While it is still experimental and I
don't recommend using it in critical projects just yet, giving it
a try should be straightforward and any feedback is appreciated.
What I mean by "should be straightforward", is that the only
thing `-preview=in` will complain about is `in ref` (it triggers
The main issue at the moment is that, if you use `dub`, you need
to have control over the dependencies to add a configuration, or
use `DFLAGS="-preview=in" dub` in order for it to work. Working
on a fix to that right now.
For reference, this is what adapting code to use `-preview=in`
feels like in my project:
You can see that I added it pretty much everywhere the type
`Hash` was used, because `Hash` is a 64 bytes struct but I needed
to support rvalues.
More information about the Digitalmars-d-learn