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?
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.
MAX_VALUE or about 2 billion regardless of the type of the array.
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..
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.
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With