C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Halfway between 'variant' and 'any'

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Tue, 3 Jan 2023 10:25:29 -0500
On Tue, Jan 3, 2023 at 3:21 AM Edward Catmur via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On Tue, 3 Jan 2023, 07:38 Frederick Virchanza Gotham via Std-Proposals, <
> std-proposals_at_[hidden]> wrote:
>
>> On Monday, January 2, 2023, Edward Catmur <ecatmur_at_[hidden]> wrote:
>>
>>>
>>> You could accomplish the inplace part with an appropriate allocator.
>>>
>>
>> If the allocator fails to allocate because the buffer is too small, then
>> this problem can be detected at runtime and we can throw an exception. But
>> with the classes I wrote, we can catch this at compile time either with
>> 'static_assert' or a concept constraint.
>>
>
> Allocators are typed. Such an allocator just needs to refuse to rebind to
> a T that is too large or too aligned.
>

Sadly, "use a different allocator" does *not* suffice to give you the
in-place allocation strategy. This is because "an allocator is a handle to
a heap <https://www.youtube.com/watch?v=0MdSJsCTRkY&ab_channel=CppNow>."
You need some way for the allocator (which is a value type, and will be
copied around quite a bit inside the internals of the STL) to point to the
place-where-the-memory-should-come-from (which in this case is "inside
*this* specific polymorphic_value object, and not inside *that* one (unless
of course the polymorphic_value object is copied or moved, in which case we
*do* mean *that* one)." The allocator model is not designed to work with
allocators that are, themselves, heaps (and thus not value types).
Strongly recommend watching my talk linked above, even though it is 90
minutes.

It's quite possible to write an inplace_any, inplace_function
<https://github.com/WG21-SG14/SG14/blob/master/SG14/inplace_function.h>,
inplace_unique_function, and so on, but you can't do it by just abusing the
allocator model; that physically will not work — neither in theory, nor in
practice on any mainstream implementation.

–Arthur

Received on 2023-01-03 15:25:42