从一种类型到另一种类型的memcpy.之后我们如何到达目的地? [英] memcpy from one type to another type. How do we access the destination afterwards?

查看:48
本文介绍了从一种类型到另一种类型的memcpy.之后我们如何到达目的地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

标头< cstring> 的内容和含义与C标准库标头< string.h> 相同.

The contents and meaning of the header <cstring> are the same as the C standard library header <string.h>.

C标准指定:

7.24.1/3对于本节中的所有功能,每个字符都应被解释为具有无符号字符类型(因此,每个可能的对象表示形式都是有效的并且具有不同的值).

7.24.1/3 For all functions in this subclause, each character shall be interpreted as if it had the type unsigned char (and therefore every possible object representation is valid and has a different value).

因此,要回答您的问题:是的,行为已定义.

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:

6.5/6 [...]如果使用memcpy或memmove将值复制到没有声明类型的对象,或复制为字符类型数组,则有效类型为对于该访问和不修改该值的后续访问而言,修改后的对象是复制值的对象的有效类型(如果有).[...]

6.5/6 [...] If a value is copied into an object having no declared type using memcpy or memmove, or is copied as an array of character type, then the effective type of the modified object for that access and for subsequent accesses that do not modify the value is the effective type of the object from which the value is copied, if it has one. [...]

该规则不适用,因为 u16 中的对象确实具有声明的类型

This rule doesn't apply, because objects in u16 do have a declared type

这篇关于从一种类型到另一种类型的memcpy.之后我们如何到达目的地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆