C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Polymorphic operator new and polymorphic values

From: Hans Åberg <haberg_1_at_[hidden]>
Date: Wed, 30 Apr 2025 19:59:03 +0200
> On 30 Apr 2025, at 19:36, Ville Voutilainen <ville.voutilainen_at_[hidden]> wrote:
>
> On Wed, 30 Apr 2025 at 20:31, Hans Åberg <haberg_1_at_[hidden]> wrote:
>>
>>
>>> On 30 Apr 2025, at 19:11, Ville Voutilainen <ville.voutilainen_at_[hidden]> wrote:
>>>
>>> On Wed, 30 Apr 2025 at 20:04, Hans Åberg via Std-Proposals
>>> <std-proposals_at_[hidden]> wrote:
>>>>
>>>> This is a rather long video. Do you have something more succinct?
>>>
>>> A std::polymorphic<B>, when initialized with an in-place value of D,
>>> type-erases the D but copies of the std::polymorphic copy a D.
>>
>> If that is enough for building my type val<A>, that is all I need. The example you gave looks right for that purpose.
>
> It is indeed enough.

I must try it out to be sure. But C++26 is fine with me. :-)

> And it has the advantage over a polymorphic
> cloning function that a polymorphic cloning function needs
> to decide how the object is allocated, whereas for use with
> std::polymorphic, all your type needs to be is to be copyable,
> and various different allocation strategies can be employed. That
> makes the combination more flexible, while requiring
> much less from your type A. You get polymorphic copies and the base
> interface, and all you need to opt in to that is to
> make your type copyable.

I have only had the need for different allocation strategies with GC references: different forms of reference counting, and Boehm GC.

With polymorphic values, that is not needed. Also, when converting from the reference type to values, I found a couple of semantic errors that had passed the “make check” that nevertheless had to be corrected. I think, therefore, that GC references should be avoided. Possibly they can be replaced by ordinary references if values are systematically used for the polymorphism.

> Welcome to the brave new world that type erasure makes possible, in
> C++26. Stop making your polymorphic derived classes
> noncopyable, make them copyable, and use them with std::polymorphic. :)

I have actually found it more useful to not use abstract or non-copyable classes.

Received on 2025-04-30 17:59:20