C++ Logo

std-discussion

Advanced search

Re: Size of heap allocated array

From: Marcin Jaczewski <marcinjaczewski86_at_[hidden]>
Date: Tue, 14 Apr 2026 11:42:06 +0200
wt., 14 kwi 2026 o 11:04 Yongwei Wu <wuyongwei_at_[hidden]> napisaƂ(a):
>
> I think it can work on pointers to (an array of) non-trivially-destructible objects. Maybe nobody finds a real usage scenario for this, thus no one has proposed it?
>

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?

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[]`?

> On Tue, 14 Apr 2026 at 16:47, Marcin Jaczewski via Std-Discussion <std-discussion_at_[hidden]> wrote:
>>
>> If I have a pointer that I can call `delete[]` on it, then why does
>> the standard not allow
>> getting the size of this storage aside in case of deleting it?
>> like:
>>
>> ```
>> auto* p = new Foo[100]{};
>> auto size = std::get_allocated_elements(p);
>> delete[] p;
>> assert(size == 100);
>> ```
>>
>> Only case where I could see this not working is `new char[]` as it could skip
>> this metadata as no destructor call is needed for elements.
>>
>> There are other limitations that prevent the standard to have it?
>> --
>> Std-Discussion mailing list
>> Std-Discussion_at_[hidden]
>> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>
>
>
> --
> Yongwei Wu
> URL: http://wyw.dcweb.cn/

Received on 2026-04-14 09:42:21