Home >Backend Development >C++ >Can memcpy be Used to Construct a Trivially-Copyable Object in C ?

Can memcpy be Used to Construct a Trivially-Copyable Object in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-19 20:32:02637browse

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:

  • Creation of array of char, unsigned char, or std::byte
  • malloc, calloc, realloc, operator new, operator new[]
  • std::allocator::allocate
  • memmove (after copying source storage to a temporary area)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn