如何使用aligned_storage和polymorphism来避免未定义的行为

时间:2017-05-29 03:18:48

标签: c++ c++11 reinterpret-cast

我有一些基本上这样做的代码:

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;

我非常怀疑这是一个定义明确的行为。如果它确实是未定义的行为,我该如何解决?在执行reinterpret_cast的代码中,我只知道基类的类型。

另一方面,如果在所有情况下都有明确定义的行为,为什么这样做又如何?

仅保留对包含对象的引用不适用于此处。在我的代码中,我想在类型擦除列表中应用SBO,其中类型由我的库的用户创建,并且基本上扩展了Base类。

我在模板函数中添加元素,但在读取它的函数中,我无法知道Derived类型。我使用基类的全部原因是因为我只需要在我的代码中使用forward函数来读取它。

以下是我的代码:

union Storage {
    // not used in this example, but it is in my code
    void* pointer;

    template<typename T>
    Storage(T t) noexcept : storage{} {
        new (&storage) T{std::move(t)}
    }

    // This will be the only active member for this example
    std::aligned_storage<16, 8> storage = {};
}; 

template<typename Data>
struct Base {
    virtual Data forward();
};

template<typename Data, typename T>
struct Derived : Base<Data> {
    Derived(T inst) noexcept : instance{std::move(inst)} {}

    Data forward() override {
        return instance.forward();
    }

    T instance;
};

template<typename> type_id(){}
using type_id_t = void(*)();

std::unordered_map<type_id_t, Storage> superList;

template<typename T>
void addToList(T type) {
    using Data = decltype(type.forward());

    superList.emplace(type_id<Data>, Derived<Data, T>{std::move(type)});
}

template<typename Data>
auto getForwardResult() -> Data {
    auto it = superList.find(type_id<Data>);
    if (it != superList.end()) {
        // I expect the cast to be valid... how to do it?
        return reinterpret_cast<Base<Data>*>(it->second.storage)->forward();
    }

    return {};
}

// These two function are in very distant parts of code.
void insert() {
    struct A { int forward() { return 1; } };
    struct B { float forward() { return 1.f; } };
    struct C { const char* forward() { return "hello"; } };

   addToList(A{});
   addToList(B{});
   addToList(C{});
}

void print() {
   std::cout << getForwardResult<int>() << std::endl;
   std::cout << getForwardResult<float>() << std::endl;
   std::cout << getForwardResult<const char*>() << std::endl;
}

int main() {
   insert();
   print();
}

3 个答案:

答案 0 :(得分:3)

不确定使用基类类型是否需要reinterpret_cast的确切语义,但您始终可以这样做,

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

auto derived_ptr = new (&storage) Derived{};
auto base_ptr = static_cast<Base*>(derived_ptr);

std::cout << base_ptr->forward() << std::endl;

另外,为什么在代码中使用带有auto&&引用的base

如果您只知道代码中基类的类型,那么考虑在aligned_storage

的抽象中使用一个简单的特征
template <typename Type>
struct TypeAwareAlignedStorage {
    using value_type = Type;
    using type = std::aligned_storage_t<sizeof(Type), alignof(Type)>;
};

然后您现在可以使用存储对象来获取它所代表的类型

template <typename StorageType>
void cast_to_base(StorageType& storage) {
    using DerivedType = std::decay_t<StorageType>::value_type;
    auto& derived_ref = *(reinterpret_cast<DerivedType*>(&storage));
    Base& base_ref = derived_ref;

    base_ref.forward();
}

如果您希望这与完美转发一起使用,那么请使用简单的转发特征

namespace detail {
    template <typename TypeToMatch, typename Type>
    struct MatchReferenceImpl;
    template <typename TypeToMatch, typename Type>
    struct MatchReferenceImpl<TypeToMatch&, Type> {
        using type = Type&;
    };
    template <typename TypeToMatch, typename Type>
    struct MatchReferenceImpl<const TypeToMatch&, Type> {
        using type = const Type&;
    };
    template <typename TypeToMatch, typename Type>
    struct MatchReferenceImpl<TypeToMatch&&, Type> {
        using type = Type&&;
    };
    template <typename TypeToMatch, typename Type>
    struct MatchReferenceImpl<const TypeToMatch&&, Type> {
        using type = const Type&&;
    };
}

template <typename TypeToMatch, typename Type>
struct MatchReference {
    using type = typename detail::MatchReferenceImpl<TypeToMatch, Type>::type;
};

template <typename StorageType>
void cast_to_base(StorageType&& storage) {
    using DerivedType = std::decay_t<StorageType>::value_type;
    auto& derived_ref = *(reinterpret_cast<DerivedType*>(&storage));
    typename MatchReference<StorageType&&, Base>::type base_ref = derived_ref;

    std::forward<decltype(base_ref)>(base_ref).forward();
}

如果您正在使用类型擦除来创建派生类类型,然后将其添加到同质容器中,您可以执行类似这样的操作

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

/**
 * An abstract base mixin that forces definition of a type erasure utility
 */
template <typename Base>
struct GetBasePtr {
public:
    Base* get_base_ptr() = 0;
};

template <DerivedType>
class DerivedWrapper : public GetBasePtr<Base> {
public:
    // assert that the derived type is actually a derived type
    static_assert(std::is_base_of<Base, std::decay_t<DerivedType>>::value, "");

    // forward the instance to the internal storage
    template <typename T>
    DerivedWrapper(T&& storage_in)  { 
        new (&this->storage) DerivedType{std::forward<T>(storage_in)};
    }

    Base* get_base_ptr() override {
        return reinterpret_cast<DerivedType*>(&this->storage);
    }

private:
    std::aligned_storage_t<sizeof(DerivedType), alignof(DerivedType)> storage;
};

// the homogenous container, global for explanation purposes
std::unordered_map<IdType, std::unique_ptr<GetBasePtr<Base>>> homogenous_container;

template <typename DerivedType>
void add_to_homogenous_collection(IdType id, DerivedType&& object) {
    using ToBeErased = DerivedWrapper<std::decay_t<DerivedType>>;
    auto ptr = std::unique_ptr<GetBasePtr<Base>>{
        std::make_unique<ToBeErased>(std::forward<DerivedType>(object))};
    homogenous_container.insert(std::make_pair(id, std::move(ptr)));
}

// and then
homogenous_container[id]->get_base_ptr()->forward();

答案 1 :(得分:2)

你可以简单地做

auto* derived = new (&storage) Derived{};
Base* base = derived;

所以没有reinterpret_cast

答案 2 :(得分:0)

在“简单”的例子中,由于你是从派生到基础的,你可以使用static_castdynamic_cast

更复杂的用例将以泪流满面,因为基指针的基础值和指向同一对象的派生指针不必相等。它今天可能有用,但明天就失败了:

  1. reinterpret_cast不能很好地继承,尤其是多重继承。如果您从多个base继承并且第一个基类具有大小(或者如果未执行空基本优化则没有大小),则来自不相关类型的第二个基类的reinterpret_cast将不应用该偏移。
  2. 重载不能很好地覆盖。模板化的类不应该有虚方法。使用虚拟方法的模板化类不应使用过多的类型推导。
  3. 未定义的行为是在C ++中指定MI的方式的基础,并且是不可避免的,因为您正在尝试获取您认为已擦除的某些内容(在编译时)(在编译时)。只需删除该类中的每个virtual关键字,并使用模板实现所有内容,一切都会更加简单和正确。
  4. 您确定派生类对象可以容纳16个字节吗?您可能需要一些static_assert
  5. 如果您愿意忍受虚拟功能引入的性能损失,为什么要关注对齐?