Strict capacity of array
Ali Çehreli
acehreli at yahoo.com
Fri Dec 13 11:10:59 PST 2013
On 12/13/2013 10:47 AM, FreeSlave wrote:
> Suppose some class contains slice (dynamic array) as data member.
> Constructor takes integer value that defines the size of data should be
> allocated. After object was constructed size of slice never changes by
> design.
>
> Dynamic arrays are allocated with extra space that we can know from
> 'capacity' property. But how can I allocate exactly as much elements as
> I want? Because in case described above we don't need extra space.
If it is not maintained by you, you can never be sure. There is
arr.reserve(N) that ensures that much room without placing .init
elements on the space.
> I know it's possible to use malloc in constructor and free in
> destructor. But what if I want to expose inner slice by shallow copy
> (i.e. by copying pointer and size, but not underlined data) then use it
> just like usual dynamic array whose lifetime does not depend on lifetime
> of an object it belongs and is managed by GC?
That is supported:
auto slice = rawPtr[0..number_of_elements];
Ali
More information about the Digitalmars-d-learn
mailing list