How to allocate arrays of objects?
Meta via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Feb 11 09:23:50 PST 2016
On Thursday, 11 February 2016 at 09:02:30 UTC, Jacob Carlborg
wrote:
> On 2016-02-11 05:34, Adam D. Ruppe wrote:
>> On Thursday, 11 February 2016 at 04:31:12 UTC, cy wrote:
>>> as[0..$] = new A();
>>>
>>> before accessing .stuff on as[0].
>>
>> Loop through it and allocate each one rather than trying to do
>> it in a
>> one liner like that.
>
> What about this?
>
> as[] = new A();
>
> Or will that allocate a new one for each element?
import std.stdio;
class Test
{
int n;
int m;
}
void main()
{
auto testArr = new Test[](5);
testArr[] = new Test();
foreach (ref test; testArr)
{
writeln(cast(void*)test);
}
}
Output:
2A41010
2A41010
2A41010
2A41010
2A41010
Not really surprising, I guess. You can always do `generate(() =>
new Test()).take(5).array`.
More information about the Digitalmars-d-learn
mailing list