mardi 28 avril 2020

C++: Is memcpy to POD based sub-object UB?

Let's go to the code:

extern "C" {
#include "pod-struct-T.h"
#include "malloc-and-initialize-one-T.h"
}

struct TCpp : T
{
   TCpp()
   {
      T* ptr_t = malloc_and_initialize_one_T();
      T* this_t = static_cast<T*>(this);
      std::memcpy(this_t, ptr_t, sizeof(T));
      free(ptr_t);
   }
};

How many UBs is there in this piece of code (for both C++03 and C++11; or for C++20 if something has change after its revisited memory model) or doing that memcpy is just fine? In case it is UB, is it at least portable among major compilers? (gcc, clang, intel, etc).

DISCLAIMER: Yes I know..., it's ugly, but don't ask why I need to do this.

Aucun commentaire:

Enregistrer un commentaire