Search code examples
dvariant

Behavior of std.variant with large types


According to the docs:

You may want to use VariantN directly with a different maximum size [from Variant] either for storing larger types, or for saving memory.

I assumed this meant that a Variant would not accept large structs, yet the following passes:

struct S {
  long[2048] vals;
}

static assert(Variant.allowed!S);

So what exactly happens when I stick a large type like S in a standard Variant? Does the S automatically get boxed?


Solution

  • Note that allowed only checks the list of types, not the size.

    But with a large thing, it gets copied into a heap thing: line 627 of variant.d's source code show it. If the size fits in the store, it is stored right here. Otherwise, a heap copy is created and a pointer to that is stored.

    So yeah, it is basically boxed as needed.