我有围绕 int 的新类型,以及包含这些新类型的类。
class IndexA {
int i;
};
class A {
IndexA index;
};
// this mimic exactly the hierarchy of `A`
struct IndexB {
int i;
};
struct B {
IndexB index;
};
鉴于 A
和 B
共享完全相同的二进制布局,以下代码是否包含未定义的行为或是否安全?
std::vector<A> vfoo {...};
std::vector<B> vbar {
std::move(
reinterpret_cast<std::vector<B>&>(vfoo)
)
};
我希望能够从 std::vector<A>
进行零复制移动转换至std::vector<B>
.有可能吗?
在我的代码中:
-
A
和B
实际上只是int
的包装,因此它们具有完全相同的二进制表示。 - 结构体
A
仅包含IndexA
的混合,std::optional<IndexA>
,std::variant<IndexA, other types like IndexA>
, 或std::vector<IndexA or std::optional<IndexA>, …>
.我认为我可以假设它们具有相同的表示形式。 -
B
是A
的严格拷贝,其中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>
tostd::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;
}
是否 A
或 B
union 成员被激活没关系。无论如何,我们都可以访问任何一个成员。
请注意,这通常不适用于所有 union ,而仅适用于标准布局结构的这种特殊情况,特别是其公共(public)初始序列中的成员。
关于c++ - 当这些对象具有相同的二进制表示时,将两个不相关的对象 vector `reinterpret_cast` 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66334299/