dimanche 28 mai 2017

How to avoid undefined behaviour with aligned_storage and polymorphism

I have some code that basically do this:

struct Base {
    virtual ~Base() = default;
    virtual int forward() = 0;
};

struct Derived : Base {
    int forward() override {
        return 42;
    }
};

typename std::aligned_storage<sizeof(Derived), alignof(Derived)>::type storage;

new (&storage) Derived{};
auto&& base = reinterpret_cast<Base*>(&storage);

std::cout << base.forward() << std::endl;

I highly doubt it's well defined behaviour. If it's indeed undefined behaviour, how can I fix it? In the code that do the reinterpret_cast, I only know the type of the base class.

Aucun commentaire:

Enregistrer un commentaire