betterC generate dynamic array throw Error: TypeInfo cannot be used with -betterC
Paul Backus
snarwin at gmail.com
Wed Oct 17 16:50:36 UTC 2018
On Wednesday, 17 October 2018 at 07:01:21 UTC, test wrote:
>
> test1:
> --------------------
> module test1;
> import test2;
> enum X = getR(1,3);
> void main(string[] args){}
>
> test2:
> --------------------
> module test2;
> struct R {
> int i;
> }
> R[] getR(int a, int b){
> R[] r;
> r ~= R(a);
> r ~= R(b);
> return r;
> }
You can't append to an array in betterC code, because making
space for the new elements requires allocating memory, and that
uses the GC.
In theory, since you're only using the GC during CTFE, it
shouldn't be a problem, but the D compiler doesn't *know* that's
what you're doing, so it has to assume the function could be
called at runtime--which would be an error.
If you're willing to give up on computing `X` at compile time,
you could rewrite getR to allocate manually, with `malloc`:
R[] getR(int a, int b)
{
import core.stdc.stdlib: malloc;
R* rp = cast(R*) malloc(2 * R.sizeof);
R[] r = rp[0 .. 2];
r[0] = R(a);
r[1] = R(b);
return r;
}
More information about the Digitalmars-d-learn
mailing list