C++ Logo

std-proposals

Advanced search

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

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Wed, 30 Apr 2025 17:27:17 +0100
On Wed, 30 Apr 2025 at 17:24, Jason McKesson via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> On Wed, Apr 30, 2025 at 12:00 PM Hans Ã…berg <haberg_1_at_[hidden]> wrote:
> >
> >
> > > On 30 Apr 2025, at 17:55, Jason McKesson via Std-Proposals <std-proposals_at_[hidden]> wrote:
> > > You can say that `polymorphic` is more cumbersome than a bespoke
> > > solution, but it solves your problem in its entirety.
> >
> > Can you give an example of how it is supposed to work?
>
> It's pretty simple and straightforward.
>
> You gave the example of:
>
> ```
> class A {
> virtual A* new_p(void* p) const& { return new A(*this); }
> };
>
> class B : A {
> virtual B* new_p(void* p) const& { return new B(*this); }
> };
>
> class C : A {
> // No new_p
> };
>
> A* bp = new B, cp = new C;
> bp->new_p(); // Gets a copy of *bp
> cp->new_p(); // Gets a copy of A(*cp)
>
> ```
>
> So, using `std::polymorphic`, none of those classes would explicitly
> need a virtual function to invoke copying. So it would look like:
>
> ```
> class A
> {
> public:
> virtual ~A(){}
> };
>
> class B : A
> {
> /*stuff*/
> };
>
> class C : A
> {
> /*stuff*/
> };
>
> std::polymorphic<A> pb{std::in_place_type_t<B>, /*arguments to B()*/};
> std::polymorphic<A> pc{std::in_place_type_t<C>, /*arguments to C()*/};
>
> auto copyb = pb; //invokes copy constructor of `B`.
> auto copyc = pc; //invokes copy constructor of `C`.
> ```
>
> And if you want to do memory allocation/deallocation yourself instead
> of relying on `operator new`, `std::polymorphic` not only provides it,
> but it can impose that allocator on any type. That is, `A`, `B`, and
> `C` don't get a say in how allocation is done. Which is better than
> your proposal, since yours binds the means of allocation to the type
> itself.

Yeah the nice thing about std::polymorphic is that you don't need to
implement a clone function, it generates one for you out of the copy
constructor.

Received on 2025-04-30 16:27:33