简体   繁体   English

可以使用 std::bit_cast 从 std::span 转换<A>到 std::span<B>并像访问对象 B 一样访问吗?</a>

[英]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类型的对象,如果不允许以这种方式访问AB ,这违反了严格别名。 And in your example, they are not.在你的例子中,它们不是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 带有 std::array 的 std::bit_cast - std::bit_cast with std::array C++11 中 std::bit_cast 的安全等效项 - Safe equivalent of std::bit_cast in C++11 当B从A继承时,std :: function &lt;void(const A&)&gt;不能转换为std :: function &lt;void(const B&)&gt; - std::function< void ( const A & )> can't cast to std::function< void ( const B & ) > when B inherits from A 是否已经有一个 constexpr std::bit_cast 与 g++ 一起使用 - Is there already a constexpr std::bit_cast to use with g++ 通过 std::bit_cast()ed 指针对访问进行别名访问 - Aliasing accesses through a std::bit_cast()ed pointer C++20 特性 std::bit_cast:重新解释类型 from 到 type to 时值会发生什么 - C++20 feature std::bit_cast : what happens to the value while reinterpreting type from to type to std::bit_cast 和 std::start_lifetime_as 之间有什么有用的区别吗? - Any useful difference between std::bit_cast and std::start_lifetime_as? static_cast 之间有区别吗<unsigned> (有符号) vs std::bit_cast<unsigned> (签)? - Is there difference between static_cast<unsigned>(signed) vs std::bit_cast<unsigned>(signed)? 文件 I/O 中的 std::bit_cast 与 reinterpret_cast - std::bit_cast vs reinterpret_cast in file I/O std::bit_cast 生成多个值的值表示的示例是什么? - What would be an example where std::bit_cast produces a value representation of multiple values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM