Creating an array of default-constructed class instances

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


On Sunday, 10 February 2013 at 06:14:37 UTC, 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?

The difference is that C++ will *place* the instances inside the 
vector. A *true* C++ equivalent would be to declare:
std::vector<Thing*> things(N);

As you can see, same problem.

Honestly, there are a lot of fancy ways to go around the problem, 
but quite frankly,I think simple is best:

//----
auto myThings = new Thing[](N);
foreach(ref aThing; myThings)
     aThing = new Thing();
//-----

It's not fancy, but it gets the job done. You won't confuse 
anyone with the code, and there is very little risk of subtle 
bugs (appart from forgetting the ref in the foreach loop.


More information about the Digitalmars-d-learn mailing list