Home >Backend Development >C++ >Can memcpy be Used to Construct a Trivially-Copyable Object in C ?
Constructing a Trivially-Copyable Object with memcpy
When working with C , developers may encounter questions regarding the validity of using memcpy to copy the representation bytes of an object. Specifically, doubt arises whether this act constitutes object construction or assignment.
This question remains unresolved, as the C standard does not explicitly address this scenario. However, certain proposals and discussions provide guidance on the matter.
Official Standard's Perspective
The current C 14 draft standard states that: "An object is created [...] by a definition, by a new-expression, or by the implementation when needed."
Furthermore, the existing clauses addressing the copying of trivial copyable types (e.g., 3.9 [basic.types]) primarily focus on copying between already instantiated objects.
Proposal p0593
The proposal p0593 attempts to address this issue and define the implicit creation of objects for low-level object manipulation. It proposes that objects of sufficiently trivial types be automatically created within newly allocated storage, ensuring well-defined behavior.
According to p0593, the following operations should implicitly create objects:
Other Considerations
The discussion on [ub] Type punning to avoid copying further highlights the complexity of this topic.
Overall, the current guidance on this subject is open to interpretation, but proposals such as p0593 aim to provide clarity and defined behavior for these operations.
The above is the detailed content of Can memcpy be Used to Construct a Trivially-Copyable Object in C ?. For more information, please follow other related articles on the PHP Chinese website!