#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_cast
ed 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.