c++ - 当这些对象具有相同的二进制表示时,将两个不相关的对象 vector `reinterpret_cast` 是否安全?

标签 c++ casting

我有围绕 int 的新类型,以及包含这些新类型的类。

class IndexA {
    int i;
};
class A {
    IndexA index;
};

// this mimic exactly the hierarchy of `A`
struct IndexB {
    int i;
};
struct B {
    IndexB index;
};

鉴于 AB共享完全相同的二进制布局,以下代码是否包含未定义的行为或是否安全?

std::vector<A> vfoo {...};
std::vector<B> vbar {
    std::move(
        reinterpret_cast<std::vector<B>&>(vfoo)
    )
};

我希望能够从 std::vector<A> 进行零复制移动转换至std::vector<B> .有可能吗?

在我的代码中:

  • AB实际上只是 int 的包装,因此它们具有完全相同的二进制表示。
  • 结构体A仅包含 IndexA 的混合, std::optional<IndexA> , std::variant<IndexA, other types like IndexA> , 或 std::vector<IndexA or std::optional<IndexA>, …> .我认为我可以假设它们具有相同的表示形式。
  • BA 的严格拷贝,其中 IndexA 的每个实例替换为 IndexB .字段顺序保持不变。

最佳答案

Is it safe to reinterpret_cast two unrelated vector of objects when those objects have the same binary representation?

不,这不安全。示例程序的行为未定义。

I would have liked to be able to do a zero copy move transformation from std::vector<A> to std::vector<B>. Is it possible?

不,这是不可能的。


您可以做的并且有点接近您正在尝试的事情是拥有这些类型的 union vector :

union IndexAB {
    IndexA A;
    IndexB B;
};

std::vector<IndexAB> vfoo {...};
for (IndexAB& u : vfoo) {
    std::cout << u.A.i;
    u.B.i = 42;
}

是否 AB union 成员被激活没关系。无论如何,我们都可以访问任何一个成员。

请注意,这通常不适用于所有 union ,而仅适用于标准布局结构的这种特殊情况,特别是其公共(public)初始序列中的成员。

关于c++ - 当这些对象具有相同的二进制表示时,将两个不相关的对象 vector `reinterpret_cast` 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66334299/

相关文章:

c++ - C++11 中流的 vector

c++ - 在没有 reverse 函数的情况下反转字符串 vector

c++ - 如何在类中初始化动态数组?

swift - 遍历设置为某种类型的 NSObject

.net - VB.NET: bool 值来自 `Nothing` 有时是 `false` 有时是 Nullreference-Exception

javascript - 在 QML 中加入 2 个字符串

c++ - 无法使用 Microsoft Visual Studio 2010 构建我的代码

c# - C# 中的动态转换

c++ - 从 ‘const int*’ 到 ‘int*’ 的无效转换

c++ - 使用 RAW 套接字读取 ICMP 响应