C++ Logo

std-discussion

Advanced search

Re: Size of heap allocated array

From: Marcin Jaczewski <marcinjaczewski86_at_[hidden]>
Date: Tue, 14 Apr 2026 16:30:41 +0200
wt., 14 kwi 2026 o 16:11 Jan Schultke <janschultke_at_[hidden]> napisaƂ(a):
>
>
>>
>> Real usage for me of this feature would be reduce size of
>> `std::vector` as in this case you could avoid `capacity` duplication
>> in vector.
>> Of corse this will work only if allocator used `new[]` instead other
>> manual handling, but even in this case allocator should perhaps know
>> how big array is?
>
>
> Any container can already do this by rebinding and putting additional header information in front of the allocation. However, it's more work and means that accessing the capacity requires memory indirection, which probably slows down operations like push_back that need to check whether the capacity is sufficient.
>

Right, but in this case why not put capacity at the end where
`push_back` try access memory? :D
```
cap = *(int*)&data[size];
```
bit hackly but only touches the same cache region as the rest of
`push_back` code.

>
>>
>> Another case is recent `std-big-int` discursion on proposal mailing
>> list and its reference implantation:
>> https://github.com/eisenwave/std-big-int
>>
>> where we have members like:
>> ```
>> std::uint32_t m_capacity; //
>> 0 = static storage, >0 = heap capacity
>> std::uint32_t m_size_and_sign; //
>> bit 31 = sign, bits 0-30 = limb count
>> data_type m_storage;
>> BEMAN_BIG_INT_NO_UNIQUE_ADDRESS allocator_type m_alloc;
>> ```
>> Idea was if we have static storage then `m_capacity` is pointless, if
>> we have heap then it could be on heap too.
>> But then if its on heap do it not already have this value to handle `delete[]`?
>
>
> It's not pointless; it's a trade-off. In the 64-bit case, removing the capacity here is also buying you no size reduction because m_storage is aligned to 64 bits anyway, so you'd end up with a 32-bit size and 32 bits of padding.
>
> In the 32-bit case, it's not so obvious, but having direct and unconditional access to the capacity buys you something.

Ok, probably in the case of a tagged pointer it could make more sense
to try to compress it.

Received on 2026-04-14 14:30:54