当前位置 : 主页 > 编程语言 > c++ >

结构赋值可以重叠类似于memmove()还是像memcpy()这样的结构赋值?

来源:互联网 收集:自由互联 发布时间:2021-06-23
在标准C库中复制数据区有两种不同的功能,memmove()用于重叠存储区,memcpy()用于不相交的非重叠存储区. C标准对结构分配的说法如下: struct thing myThing = {0};struct thing *pmyThing = myThing;myThin
在标准C库中复制数据区有两种不同的功能,memmove()用于重叠存储区,memcpy()用于不相交的非重叠存储区.

C标准对结构分配的说法如下:

struct thing myThing = {0};
struct thing *pmyThing = &myThing;

myThing = *pmyThing;     // assign myThing to itself through a pointer dereference.

结构分配是否遵循memmove()或memcpy()或其自身规则的规则,只要涉及重叠的内存区域?

C标准的第6.5.16.1节(“简单分配”)(从N1548草案中读取)规定:

In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.

If the value being stored in an object is read from another object that overlaps in any way the storage of the first object, then the overlap shall be exact and the two objects shall have qualified or unqualified versions of a compatible type; otherwise, the behavior is undefined.

C标准没有规定编译器如何实现简单赋值.但如果重叠是精确的并且类型兼容,则允许源和目标之间的重叠.自我分配(无论是否通过指针)满足此要求,因此行为是明确定义的.

网友评论