Creating an array of default-constructed class instances

monarch_dodra monarchdodra at gmail.com
Sun Feb 10 03:18:51 PST 2013


On Sunday, 10 February 2013 at 09:48:04 UTC, Jos van Uden wrote:
> On 10-2-2013 7:14, Simon wrote:
>> Hi, I'm new to the D programming language.  Overall I'm liking
>> things very much, but I'm still getting the hang of a few 
>> things.
>>
>> Here's a basic programming pattern: I have a class called 
>> Thing,
>> and while I'm coding I decide I need N Thing instances.
>>
>> In C++ that's a matter of
>>
>> std::vector<Thing> things(N);
>>
>> In python, I can use a list comprehension.
>>
>> things = [Thing() for _ in range(N)]
>>
>> However, the obvious D version doesn't work.
>>
>> auto things = new Thing[N];
>>
>> Because Thing.init is null, this produces an array of null
>> references.  Of course, I can write a for loop to fill in the
>> array after creation, but this feels very un-D-like.  Is there 
>> a
>> straightforward way to create a bunch of class instances?
>
> import std.stdio, std.algorithm;
>
> class Thing {
>     int i;
>     this(int i) {
>         this.i = i;
>     }
> }
>
> void main()
> {
>    auto things = new Thing[10];
>    fill(things, new Thing(5));
>
>    foreach (t; things)
>         writef("%d ", t.i);
> }

HELL NO!!!!

What you did just right there is allocate a *single* thing 
_instance_  and then place 10 _references_ to that same thing in 
the array.


More information about the Digitalmars-d-learn mailing list