Questions about initialization of array of objects

Maxim Fomin maxim at maxim-fomin.ru
Sat Jan 12 11:54:46 PST 2013


On Saturday, 12 January 2013 at 19:07:38 UTC, Andrey wrote:
> I'm not sure about proper understanding of RAII idiom, but 
> should objects in array be automatically constructed during 
> array initialization?

Members of static arrays are initialized to their default values.

> Example.
>
> class ClassPoint {
>     int x,y;
> }

This is initialized to null.

> struct StructPoint {
>     int x,y;
> }

This is initialized to StructPoint(0,0).

> ClassPoint[8] arr; //static array of null references;
> StructPoint[8] arr2;
>
> arr[0].x=1 //error, there is no object
> arr2[0].x=1 //OK.
>
> Here I have two questions:
>
> 1) Can you have automatically constructed objects with default 
> class constructor?

No. It is possible to create a wrapper struct type with "alias 
this" to ClassPoint[8], which defaults to preallocated objects, 
but as a drawback each instance of such type would default to 
same class references and this makes the hack mostly unusable.

> 2) Can you setup memory attributes for static array using 
> core.memory functions, say, to force GC not to scan this 
> portion of memory during collection?

I do not understand what you mean here.


More information about the Digitalmars-d-learn mailing list