Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does memcpy preserve a trivial object's validity?

If one has a valid object of a trivial type (in this context, a trivial type satisfies the trivially move/copy constructible concepts), and one memcpys it to a region of uninitialised memory, is the copied region of memory a valid object?

Assumption from what I’ve read: An object is only valid if it’s constructor has been called.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Copying an object of a trivial type with std::memcpy into properly sized and aligned storage will implicitly begin the lifetime of a new object at that location.

There is a category of types called implicit-lifetime type whose requirements are :

  • a scalar type, or
  • an array type, or
  • an aggregate class type, or
  • a class type that has
    • at least one trivial eligible constructor, and
    • a trivial, non-deleted destructor,
  • or a cv-qualified version of one of above types.

Trivial class types meet these requiements.

Objects of implicit-lifetime type have the property that their lifetime can be started implicitly be several functions or operations :

  • operations that begin lifetime of an array of type char, unsigned char, or std::byte, (since C++17) in which case such objects are created in the array,
  • call to following allocating functions, in which case such objects are
    • created in the allocated storage:
    • operator new
    • operator new[]
    • std::malloc
    • std::calloc
    • std::realloc
    • std::aligned_alloc (since C++17)
  • call to following object representation copying functions, in which case such objects are created in the destination region of storage or the result:
    • std::memcpy
    • std::memmove
    • std::bit_cast (since C++20)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading