如何避免具有aligned_storage和多态性的未定义行为

How to avoid undefined behaviour with aligned_storage and polymorphism

本文关键字:多态性 未定义 storage 何避免 aligned      更新时间:2023-10-16

我有一些代码基本上可以做到这一点:

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;

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


如果您只知道代码中基类的类型,请考虑在抽象中使用简单的特征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();

你可以简单地做

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

所以没有reinterpret_cast.

在你拥有的"简单"示例中,由于您是从派生转换为基,因此static_castdynamic_cast都可以。

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

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