Home > Net >  Can std::bit_cast be used to cast from std::span<A> to std::span<B> and access as if the
Can std::bit_cast be used to cast from std::span<A> to std::span<B> and access as if the

Time:11-11

#include <array>
#include <bit>
#include <span>

struct A {
    unsigned int size;
    char* buf;
};

struct B {
    unsigned long len;
    void* data;
};

int main() {
    static_assert(sizeof(A) == sizeof(B));
    static_assert(alignof(A) == alignof(B));
    std::array<A, 10> arrayOfA;
    std::span<A> spanOfA{arrayOfA};
    std::span<B> spanOfB = std::bit_cast<std::span<B>>(spanOfA);
    // At this point, is using spanOfB standard compliant?
}

I've tried accessing bit_casted span on 3 major compilers and they seem to be working as expected, but is this standard compliant?

CodePudding user response:

No. While std::span in C 23 will be defined such that it must be trivially copyable, there is no requirement that any particular span<T> has the same layout of span<U>. And even if it did, you'd still be accessing the objects of type A through a glvalue of type B, which violates strict aliasing if A and B aren't allowed to be accessed that way. And in your example, they are not.

  • Related