问题描述
uint32_t u32 = 0;
uint16_t u16[2];
static_assert(sizeof(u32) == sizeof(u16), "");
memcpy(u16, &u32, sizeof(u32)); // defined?
// if defined, how to we access the data from here on?
这是定义的行为吗?而且,如果是这样,在 memcpy
之后,我们可以使用哪种类型的指针来访问目标数据?
Is this defined behaviour? And, if so, what type of pointer may we use to access the target data after the memcpy
?
我们必须使用 uint16_t *
,因为它适合 u16
的声明的类型吗?
Must we use uint16_t*
, because that suitable for the declared type of u16
?
还是我们必须使用 uint32_t *
,因为源数据的类型(由 memcpy
复制的源数据)是 uint_32
?
Or must we use uint32_t*
, because the type of the source data (the source data copied from by memcpy
) is uint_32
?
(个人对C ++ 11/C ++ 14感兴趣.但是对诸如C之类的相关语言的讨论也会很有趣.)
(Personally interested in C++11/C++14. But a discussion of related languages like C would be interesting also.)
推荐答案
C ++标准委托给C标准:
The C++ standard delegates to C standard:
C标准指定:
因此,要回答您的问题:是的,行为已定义.
So, to answer your question: Yes, the behaviour is defined.
是的,因为 uint16_t
是对象的类型,所以 uint16_t *
是合适的.
Yes, uint16_t*
is appropriate because uint16_t
is the type of the object.
不,来源的类型无关紧要.
No, the type of the source doesn't matter.
C ++标准未将没有声明类型的对象或对象的行为指定为对象.我的解释是,有效类型是为没有声明类型的对象定义的实现.
C++ standard doesn't specify such thing as object without declared type or how it would behave. I interpret that to mean that the effective type is implementation defined for objects with no declared type.
即使在C语言中,在这种情况下,源也无关紧要.您所关注的来自C标准(草稿,N1570)的报价的更完整版本,请强调:
Even in C, the source doesn't matter in this case. A more complete version of quote from C standard (draft, N1570) that you are concerned about, emphasis mine:
该规则不适用,因为 u16
中的对象确实具有声明的类型
This rule doesn't apply, because objects in u16
do have a declared type
这篇关于从一种类型到另一种类型的memcpy.之后我们如何到达目的地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!