c++ - 如何使用 aligned_storage 和多态性避免未定义的行为

标签 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();
}

最佳答案

不确定 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();

关于c++ - 如何使用 aligned_storage 和多态性避免未定义的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44234166/

相关文章:

c++ - 如何使用 SFINAE 从 end() 方法返回 (const_)iterator

C++ 基于文本的 RPG 库存系统

android - 在 Android 上使用 JNI 使用上下文指针调用函数会导致段错误

c++ - 无法理解这个可变参数模板示例

c++ - signed int 引用的 reinterpret_cast

c++ - 使用 reinterpret_cast 的签名别名

c++ - 不确定 Dekkers 算法做错了什么

c++ - 在 C++ 中以通用的可移植方式识别类型

c++ - 为什么内联函数默认有外部链接?

c++ - reinterpret_cast 和结构对齐