Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to copy the bytes of an object out to an array and back again

Is it safe to copy the bytes of an object out to an array of unsigned char and then back again using memcpy, and does it leave the object unchanged?

That is, is the following safe for any t:

template <typename T>
void copy_back_and_forth(T& t) {
  unsigned char buf[sizeof(T)];
  std::memcpy(buf, &t, sizeof(T));
  std::memcpy(&t, buf, sizeof(T));
}

... and does it leave t unchanged?

like image 576
BeeOnRope Avatar asked Jan 22 '20 05:01

BeeOnRope


People also ask

How do you copy a byte array?

copyOf(byte[] original, int newLength) method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values.

How much can a byte array hold?

MAX_VALUE or about 2 billion regardless of the type of the array.

What does array of bytes mean?

A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..

What is the difference between bytes and byte array?

bytes and bytearrays are similar... The primary difference is that a bytes object is immutable, meaning that once created, you cannot modify its elements. By contrast, a bytearray object allows you to modify its elements. Both bytes and bytearay provide functions to encode and decode strings.


1 Answers

The value of t is guaranteed to be unchanged if T is trivially copyable type, and t is not a potentially-overlapping subobject. Standard quote from latest draft:

[basic.types]

For any object (other than a potentially-overlapping subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes ([intro.memory]) making up the object can be copied into an array of char, unsigned char, or std​::​byte ([cstddef.syn]).37 If the content of that array is copied back into the object, the object shall subsequently hold its original value.

37) By using, for example, the library functions ([headers]) std​::​memcpy or std​::​memmove.

In fact, the standard has a nearly identical example:

[ Example:

constexpr std::size_t N = sizeof(T);
char buf[N];
T obj;                          // obj initialized to its original value
std::memcpy(buf, &obj, N);      // between these two calls to std​::​memcpy, obj might be modified
std::memcpy(&obj, buf, N);      // at this point, each subobject of obj of scalar type holds its original value

— end example ]

like image 191
eerorika Avatar answered Oct 11 '22 11:10

eerorika