new T[size] vs .reserve

monarch_dodra monarchdodra at gmail.com
Sat Feb 2 13:47:42 PST 2013


On Saturday, 2 February 2013 at 19:49:39 UTC, FG wrote:
> On 2013-02-02 19:53, Namespace wrote:
>>> Are you uncomfortable, because it may allocate twice as much 
>>> space
>>> as you need (for bigger color_data)?
>>
>> Yes, that's the point.
>> Sorry, I cannot express myself very well in English.
>
> You're right. It's surprising for anyone used to dealing with 
> std::vector,
> that it actually reserves more than you specify.

FYI: std::vector will do exactly the same thing. The actual grow 
scheme may be different, but that is purelly an implementation 
detail.

Another thing to take into account: In C++, if you request 10 
bytes of allocation space, but the underlying implementation 
actually allocates a 32 byte block, you'll know nothing of it. If 
later, you want to grow those 10 bytes to 20 bytes, you'll have 
to request a new allocation.

std::vector has actually no idea how much space actually gets 
allocated. It requests a certain amount but has no idea how much 
it really gets. At best, it can tell you how much it requested.

In D, you can exploit the last drop of allocation space actually 
allocated. It is the underlying array itself that tells you how 
much space there is left.

> Another odd thing - when pushing back to a vector its capacity 
> grows:
> 1, 2, 4, 8, 16, 32 ..., but with D arrays it's like 7, 15, 31, 
> 63...
> Why 2**n - 1? What secret data is hidden after the block? ;)

The currently used size.

In C++, set::vector is a struct that has a "size" member, and a 
pointer to a payload. In D, the "size" data is embedded straight 
into the payload. Kind of like how std::string is implemented 
actually.

This has a two-fold advantage: The actual slice object is light 
(just a fat pointer). Also, when you have two (or more) slices 
that reference the same data, they *know* if or if not they can 
safelly append, without cloberring the data of another slice.

I suggest you read this:
http://dlang.org/d-array-article.html
It is a very interesting read, especially for those of us with 
C++ background.

One very (very) important thing to realize is that std::vector is 
a container. D slices are not containers: they are ranges. They 
iterate on an underlying array object, but they are not 
containers themselves.

The underlying object, the so called "dynamic array" is actually 
a obscure and hidden object you cannot access dirrectly.

There is some ambiguity between both terms, and they are often 
used interchangedbly, but to really understand what is going on, 
you need to imagine them as two different objects interacting.


More information about the Digitalmars-d-learn mailing list