C++ Logo

std-proposals

Advanced search

Re: Polymorphic object types

From: Gašper Ažman <gasper.azman_at_[hidden]>
Date: Thu, 9 Sep 2021 20:26:30 +0100
How is this much different from std::variant?

On Thu, Sep 9, 2021, 19:32 sasho648 via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> I suggest a way to have polymorphic objects.
>
> For that purpose I propose the use of union object with non aggregate
> types and no explicitly defined constructor with a single default
> initializer like follows:
>
>
>
> union polymorphic_type : A, B, C{} {};
>
> While A, B and C both should all have compatible runtime types.
>
> The type with initializer will be the one which will be used to construct
> the object but the one used to destruct it will be the last object
> constructed at this memory location (virtual destructors or UB).
>
> Obviously this newly created union type should have the same alignment
> requirements as aligned_storage_t of the most outer type.
>
> This will be useful for creating polymorphic containers.
>
> This idea is arising from the current lack of polymorphism for non dynamic
> storage duration objects.
>
> I have a code base which does something like this:
>
> struct A {
> virtual ~A();
> virtual void f() {}
> };
> struct B : A {
> virtual ~B();
> virtual void f() {}
> };
> struct C : B {
> virtual ~C();
> virtual void f() {}
> };
>
> std::aligned_storage_t<sizeof(C), alignof(C)> uninpolyobj;
>
> static A* pobj = new (&uninpolyobj) A{};
>
> Where I can then call the virtual destructor and create a new different
> object at its place (since the alignment is the same) with placement new.
>
> That is all handy at all but I wish this to be automatically handled -
> construction and destruction - which will be useful for using polymorphic
> types with containers.
>
> Thanks so much for the attention and I hope you find this feature useful.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2021-09-09 14:26:43