When D feels unfinished: union initialization and NRVO

Jacob Carlborg doob at me.com
Wed Mar 18 19:09:12 UTC 2020


On 2020-03-18 07:55, Mathias Lang wrote:

> This set of requirement led me to a few simple observations:
> - I cannot use a temporary and `cast`. Aside from the fact that most 
> casts are an admission that the type system is insufficient, it would 
> force me to pass the type by `ref` when composing, which would expose 
> the `cast` to user code, hence not `@safe`;

How would the `cast` be exposed to the user code?

> But is it really a problem ? Can't we just do the following:
> ```
> QT ret = { type: type, _confirm_t: deserialize!_confirm_t(dg, opts) };
> return ret;
> ```
> Well no, because then, NRVO is not performed anymore.

I haven't looked at the generated code, but this compiles at least:

struct QT
{
     int type;
     int _confirm_t;

     @disable this(this);
     @disable ref QT opAssign () (auto ref QT other);
}

QT foo()
{
     QT ret = { type: 1, _confirm_t: 2 };
     ret.type = 4;
     return ret;
}

void main()
{
     auto qt = foo();
}

As long as you return the same variable in all branches it compiles at 
least. If you start to return a literal in one branch and a variable in 
a different branch it will fail to compile.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list