在寻找将 sizeof(double)
char
组合为 double
的方法时,我读到了几篇文章,其中使用 std::memcpy
是推荐的方式:
char bytes[sizeof(double)];
// fill array
double d;
std::memcpy(&d, bytes, sizeof(double));
但是,我想知道为什么进一步使用 d
可以定义行为。
如果它不是一个double
,而是一个复杂的类对象,访问它肯定也不会被定义,不是吗?那么,为什么 double
会出现这种情况。
编辑:为了明确我的问题,我想指定我的目标:我想找到一种方法将多个 char
组合为 double
并进一步使用这个 double ,而不会导致未定义的行为。我不期望指定double
的值。无论如何,我认为这是不可能的,因为标准甚至没有说明任何有关大小的信息,更不用说 double
的位布局了。但是,我要求d
具有一些有效(即“可访问”)double
-值。
最佳答案
Why does type-punning using std::memcpy not cause undefined behaviour?
因为语言是这样说的(最新草案):
[basic.types]
For any object (other than a potentially-overlapping subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes ([intro.memory]) making up the object can be copied into an array of char, unsigned char, or std::byte ([cstddef.syn]). If the content of that array is copied back into the object, the object shall subsequently hold its original value.
但是请注意该规则的条件。您的代码可能具有未定义的行为,但如果复制的值最初是从另一个 double 值复制的,或者在实践中,如果该值可以从 double 值复制,则不会(除非其他规则如此规定)。
If it was not a double, but a complex class object, accessing it surely would not be defined either, would it?
取决于您所说的复杂性是什么意思。适用的条件在引用的规则中。
关于c++ - 为什么 std::memcpy (作为类型双关的替代方法)不会导致未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209852/