You could do something like this:
T foo; // your given arbitrary object
T bar; // target
unsigned char * p = reinterpret_cast<unsigned char *>(&foo); // type-punned
unsigned char * q = reinterpret_cast<unsigned char *>(&bar); // ditto
memcpy(q, p, sizeof(T)); // copy byte-wise
If T
has non-trivial properties (custom constructors, pointers to heap variables, etc.), this has lots of potential to cause trouble, but you can certainly access the raw data via those pointers. (Doing this in general may be fun for instance if you want to look at the binary representation of a double
or something like that, but in production code this should rarely come up.)
If your original object is T foo[N]
, use the size sizeof(T) * N
.
Edit: Do you mean that you want this to work for an arbitrary type or for an unknown type? If you don't know the size of T
(e.g. if you are only handed the pointer), then of course you cannot do it because you don't know how much memory is occupied. There are no "field delimiters" or anything like that stored in memory that you could inspect at runtime.