[英]Can std::bit_cast be used to cast from std::span<A> to std::span<B> and access as if there was an array of object B?
#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?我已经尝试在 3 个主要编译器上访问bit_cast
ed span
,它们似乎按预期工作,但是这个标准符合吗?
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>
.不。虽然 C++23 中的std::span
将被定义为它必须是可简单复制的,但不要求任何特定的span<T>
具有与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.即使是这样,您仍然会通过B
类型的泛左值访问A
类型的对象,如果不允许以这种方式访问A
和B
,这违反了严格别名。 And in your example, they are not.在你的例子中,它们不是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.