Jonathan Blow demo #2

bearophile via Digitalmars-d digitalmars-d at puremagic.com
Fri Dec 12 01:54:46 PST 2014


Walter Bright:

> On 12/11/2014 1:49 PM, bearophile wrote:
>> Walter Bright:
>>
>>>> struct Vec { float x = 1, y = 5, z = 9; }
>>>>
>>>> auto v = new Vec(void);
>>>> auto av = new Vec[10] = void;
>>>> auto av2 = new Vec[10] = Vec(0, 0, 0);
>>>
>>> D already does this.
>>
>> D doesn't do that, not even one of those three :-)
>
> I beg to differ:
>
>
> struct Vec { float x = 1, y = 5, z = 9; }
>
> void main()
> {
>   {
>     Vec v;
>     assert(v.x == 1 && v.y == 5 && v.z == 9);
>   }

This is not relevant in this discussion.


>   {
>     auto v = new Vec();
>     assert(v.x == 1 && v.y == 5 && v.z == 9);
>   }

This misses the point.

This code:
struct Vec { float x = 1, y = 5, z = 9; }
auto v = new Vec(void);

Means having defined a struct with explicitly statically defined 
fields, and then allocate one of it on the heap without 
initializing its fields.
It's equivalent to:

auto v = cast(Vec*)malloc(Vec.sizeof);

Also written like this if you have written a little function 
(missing in Phobos) that makes your code more DRY and hides the 
cast in a probably @trusted function:

auto v = cMalloc!Vec;

Similar code can be written if you want to use the GC heap.


>   {
>     auto v = cast(Vec*)malloc(Vec.sizeof * 10)[0..10];
>   }

This is right, but in D it's often better to use 
std.array.uninitializedArray to do that.


>   {
>     auto v = new Vec[10];
>     v[] = Vec(0,0,0);
>     assert(v[1].x == 0 && v[1].y == 0 && v[1].z == 0);
>   }
> }

This causes double initialization of the array, and I can't be 
sure the optimizer removes the first one (dmd doesn't remove it, 
and until now ldc2 doesn't remove it).

To solve this problem with Phobos code it can be added another 
std.array function like:

auto av2 = initializedArray!(Vec[])(10, Vec(0, 0, 0));

Beside constants, initializedArray also should accept a pure 
function that takes as input the index (this request is in 
Bugzilla).

So all three patterns can be realized using functions, so there's 
no need to change the D language to do all three things.

But are some of those patterns common enough to deserve to be 
supported by the language?

Bye,
bearophile


More information about the Digitalmars-d mailing list