Efficiently passing structs

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 3 21:16:03 PDT 2015


On Sunday, May 03, 2015 21:58:12 bitwise via Digitalmars-d-learn wrote:
> If I have a large struct that needs to be passed around, like a 4x4 matrix
> for example, how do I do that efficiently in D?
>
> In std.datetime, "in" is used for most struct parameters, but I'm confused
> by the docs for function parameter storage classes[1].
>
> In C++, I would pass a large struct as (const&):
> void foo(const Matrix4x4 &m);
>
> Is "in" in D the same as passing by const& in C++? The documentation
> doesn't say anything about "in" being a reference, but it doesn't say that
> "out" parameters are references either, even though it's usage in the
> example clearly shows that it is.
>
> Thanks,
>    Bit
>
> http://dlang.org/function.html#parameters

std.datetime's use of in is pointless and really should be removed. I
misunderstood it at the time I did that. in is essentially an alias for
const scope, and scope does nothing in most cases, basically making it
const, which is generally pointless for a function parameter unless you're
specifically trying to make it so that it can't be mutated inside the
function. And since scope has not even been properly designed (let alone
implemented), I would argue that using in is almost always a bad idea.

The equivalent to const& in D is const ref except that it does not accept
rvalues. So, if you want to be able to do the same, you'll have to do
something like

void foo(ref const Matrix4x4 m)
{
    ...
}

void foo(const Matrix4x4 m)
{
    foo(m);
}

D will move the argument if it can rather than copying it (e.g. if a
temporary is being passed in), which reduces the need for worrying about
copying like you tend to have to do in C++98, and I think that a lot of D
code just doesn't worry about the cost of copying structs. However, if you
have a large object that you know is going to be expensive to copy, you're
either going to have to use const ref (and thus probably duplicate the
function to allow rvalues), or you're going to need to make it a reference
type rather than having all of its data live on the stack (either by making
it so that the struct contains a pointer to its data or by making it a
class). In general, if you're dealing with a type that is going to be
expensive to copy, I'd advise making it a reference type over relying on
const ref simply because it's less error-prone that way. It's trivial to
forget to use ref on a parameter, and generic code won't use it, so it'll
generally work better to just make it a reference type.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list