简体   繁体   English

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

[英]can a struct assignment overlap similar to memmove() or is struct assignment like memcpy()?

There are two different functions for making a copy of a data area in the Standard C library, memmove() used for overlapping memory areas and memcpy() for disjoint, non-overlapping memory areas. 在标准C库中复制数据区有两种不同的功能, memmove()用于重叠存储区, memcpy()用于不相交的非重叠存储区。

What does the C standards say about struct assignment as in: C标准对结构分配的说法如下:

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

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

Does the struct assignment follow the rules for memmove() or for memcpy() or its own rules so far as overlapping memory areas are concerned? 结构分配是否遵循memmove()memcpy()或其自身规则的规则,只要涉及重叠的内存区域?

Section 6.5.16.1 ("Simple assignment") of the C standard (reading from draft N1548) states: 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. 否则,行为未定义。

The C standard doesn't specify how the compiler implements the simple assignment. C标准没有规定编译器如何实现简单赋值。 But overlap between the source and destination are permitted if the overlap is exact and the types are compatible. 但如果重叠是精确的并且类型兼容,则允许源和目标之间的重叠。 Self-assignment (whether through a pointer or not) meets this requirement, and thus the behavior is well-defined. 自我分配(无论是否通过指针)满足此要求,因此行为是明确定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM