c++ - 为什么 std::memcpy (作为类型双关的替代方法)不会导致未定义的行为?

标签 c++ language-lawyer undefined-behavior

在寻找将 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/

相关文章:

c++ - VS : Tooltip help for doxygen-style commented functions?

c++ - 并非所有类型的成员都初始化时,可以复制普通类型的类吗?

javascript - DOM - 同时事件的计时与 setTimeout

c - C 中的胖指针

c - 为什么这些构造使用增量前和增量后未定义的行为?

java - Java读取protobuf消息时出现异常

c++ - (Qt 5.4.1)此应用程序无法启动,因为它找不到或加载Qt平台插件 "xcb"

C++:使用指向 unordered_map 的指针或只是将其定义为类中此类型的成员变量?

c++11 - clang++失败,但g++成功在赋值中使用强制转换为const-unrelated-type运算符

c++ - 标准中关于超出范围指针的未定义行为的歧义