C++ Logo

std-proposals

Advanced search

Polymorphic object types

From: sasho648 <sasho648_at_[hidden]>
Date: Thu, 9 Sep 2021 21:32:07 +0300
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.

Received on 2021-09-09 13:32:22