【发布时间】:2021-11-09 06:11:58
【问题描述】:
我担心未定义的行为。您可以使用 memcpy 初始化一个可简单复制的联合类型的值吗?当我考虑将 Boost Serialization 与 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;
}
}
【问题讨论】:
标签: c++ initialization union undefined-behavior memcpy