繁体   English   中英

正在使用 memcpy 构建一个可简单复制的联合 UB 吗? 活跃的成员?

[英]Is using memcpy to construct a trivially copyable union UB? Active member?

我担心未定义的行为。 你可以使用 memcpy 初始化一个可简单复制的联合类型的值吗? 当我考虑使用带有BOOST_IS_BITWISE_SERIALIZABLE(MyUnionType)的 Boost Serialization 时出现了这个问题,我假设它使用了 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;
    }
}

从定义来看,我认为这种情况没有问题:

可简单复制的 class 是 class(使用 class、结构或联合定义):

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

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

在这种情况下,Foo 本身是可简单复制的

static_assert(std::is_trivially_copyable_v<Bar>);

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM