r/cpp • • Mar 10 '26

Deriving Type Erasure

https://david.alvarezrosa.com/posts/deriving-type-erasure/
59 Upvotes

34 comments sorted by

View all comments

Show parent comment

3

u/chengfeng-xie Mar 11 '26

For MSVC's implementation of std::any specifically, its class layout is (any#L348-L371):

struct _Small_storage_t {
    unsigned char _Data[_Any_small_space_size];
    const _Any_small_RTTI* _RTTI;
};
static_assert(sizeof(_Small_storage_t) == _Any_trivial_space_size);

struct _Big_storage_t {
    // Pad so that _Ptr and _RTTI might share _TypeData's cache line
    unsigned char _Padding[_Any_small_space_size - sizeof(void*)];
    void* _Ptr;
    const _Any_big_RTTI* _RTTI;
};
static_assert(sizeof(_Big_storage_t) == _Any_trivial_space_size);

struct _Storage_t {
    union {
        unsigned char _TrivialData[_Any_trivial_space_size];
        _Small_storage_t _SmallStorage;
        _Big_storage_t _BigStorage;
    };
    uintptr_t _TypeData;
};
static_assert(sizeof(_Storage_t) == _Any_trivial_space_size + sizeof(void*));
static_assert(is_standard_layout_v<_Storage_t>);

In the above, the _RTTI member is a pointer to a hand-rolled virtual table, and the _TypeData member is a tagged pointer (encoding whether SBO is in effect) to a type_info object. If the virtual-function approach were chosen, the _RTTI member could be eliminated, so the available SBO space would actually be the same in both approaches. So I think what matters more is the extra indirection involved in the virtual-function approach, as you mentioned.

2

u/XeroKimo Exception Enthusiast Mar 12 '26 edited Mar 12 '26

Hmm... originally I thought you'd need to replace the _RTTI field with something like a any_impl_base*, but I guess if the implementation allows you, you can interpret and launder the start of the SBO address as a any_impl_base*, in which case, yea, you would still have the full 56 bytes of SBO, otherwise, you'd only have 48 bytes.

As I thought more about it, the vtable might not even occur any penalty because the pointer would be in the cache whether you use MSVC's hand rolled vtable or using C++'s virtual functions