How to reserve memory for a slice in a struct

Steven Schveighoffer schveiguy at yahoo.com
Tue May 7 05:44:21 PDT 2013


On Tue, 07 May 2013 06:29:43 -0400, Namal <sotis22 at mail.ru> wrote:

> Hello,
>
> I am new to D. According to that power of 2 rule I want to
> reserve 2 sized chunks to my array, But how do I do that in a
> struct? Say:
>
> struct Stack(int){
>
> int a[];
>
>
> }
>
>
> Where do I put that a.reserve(2);
>
> Because right after the declaration of a I get an error
>
> Error: unexpected ( in declarator
> Error: basic type expected, not 2
> Error: found '2' when expecting ')'
> Error: no identifier for declarator a.reserve(int)
> Error: semicolon expected following function declaration
> Error: Declaration expected, not ')'

You cannot statically reserve heap space for any type.

You have two choices:

1. make 'a' a fixed sized array (this reserves space inside the struct):

int[2] a;

2. reserve space at runtime (e.g. during constructor):

this(size_t n) { a.reserve(n); }

Unfortunately, structs have no default constructor, so you can't specify  
that a *always* is reserved.

A note of caution -- reserving space via a.reserve does *not* give you  
access to the space, it just reserves a block for your use to append the  
slice into the array.  So for example:

a.reserve(2);
assert(a.length == 0); // length is still 0.
assert(a.ptr !is null); // but block has been allocated with at least 2  
elements.
a ~= 1; // pointer has not changed, a is now filling into allocated block.

If you want to reserve accessible space, set the length:

a.length = 2;

One other thing, the space you reserve is not exactly a power of 2.  It  
will be 2^^n - 1.  This is due to requirements of the array runtime.

The minimal heap space for an int array is 3.  Then it goes 7, 15, 31,  
etc.  Once you get to page size, the amount of space you can reserve grows  
linearly.  These are implementation details of the GC, so you shouldn't  
depend on this never changing.  In any case, whatever space you request,  
the GC will give you at LEAST that much.

-Steve


More information about the Digitalmars-d-learn mailing list