std::bit_cast 可以用于从 std::span<A> 转换为 std::span<B> 并像存在对象 B 的数组一样访问吗?
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?
}
我已经尝试在 3 个主要编译器上访问 bit_cast
ed span
,它们似乎按预期工作,但是否符合该标准?
没有。虽然 C++23 中的 std::span
将被定义为必须可简单复制,但不要求任何特定的 span<T>
具有与 span<U>
相同的布局。即使这样做了,您仍然会通过 B
类型的泛左值访问 A
类型的对象,如果 A
和 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?
}
我已经尝试在 3 个主要编译器上访问 bit_cast
ed span
,它们似乎按预期工作,但是否符合该标准?
没有。虽然 C++23 中的 std::span
将被定义为必须可简单复制,但不要求任何特定的 span<T>
具有与 span<U>
相同的布局。即使这样做了,您仍然会通过 B
类型的泛左值访问 A
类型的对象,如果 A
和 B
不是这样的话,这违反了严格的别名不允许以这种方式访问。在你的例子中,它们不是。