是否使用 memcpy 来构建一个微不足道的可复制联合 UB?活跃会员?



我担心未定义的行为。是否可以使用 memcpy 初始化简单可复制的联合类型的值?当我考虑将 Boost 序列化与BOOST_IS_BITWISE_SERIALIZABLE(MyUnionType)一起使用时,就出现了这种情况,我认为它使用了类似 memcpy 的东西。

#include <cstring>
enum class Foo: int {};
union Bar {
int num;
Foo foo;
};
int baz(int src) {
Bar dst;
// My understanding is that memcpy does initialize dst
// but doesn't set the active member of the union.
std::memcpy(&dst, &src, sizeof(Bar));
// My understanding is that whichever member is read
// first here becomes the active member of the union.
if (src > 42) {
return dst.num;
} else {
return (int)dst.foo;
}
}

从定义上看,我没有看到这种情况有问题:

一个平凡可复制的类是一个类(由类、结构或联合定义),它:

  • 使用隐式定义的复制和移动构造函数、复制和移动赋值以及析构函数。
  • 没有虚拟成员。
  • 它的基类和非静态数据成员(如果有)本身也是简单的可复制类型。

成员生存期 工会成员的生命周期从成员处于活动状态时开始。如果另一个成员以前处于活动状态,则其生存期结束。

在这种情况下,Foo本身是微不足道的可复制的

static_assert(std::is_trivially_copyable_v<Bar>);

所以我看不出有任何理由 UB

最新更新