Home > Software design >  Does memcpy preserve a trivial object's validity?
Does memcpy preserve a trivial object's validity?

Time:04-12

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.

CodePudding user response:

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)
  • Related