DarthRubik
DarthRubik

Reputation: 3985

Store aligned data non aligned

Suppose I have a have a class T and an array:

uint8_t array[sizeof(T)];

One thing to note is that array might have an alignment which might not be compatible with T.

Now the question is: Is there any way to store a T in array (despite the alignment issues), provided that we do not try to do any thing with the T, until we copy it from the array into a properly aligned storage space?

In other words array is just going to be a storage location, until we need to access T, at which case we copy it to proper alignment, and use the value, and copy it back into storage.

Note:

T may be trivially copyable but it is not guaranteed that T is going to be trivially copyable......it could be any class you could think of

So.....is this in any way possible (hopefully standard conforming?)

Upvotes: 0

Views: 82

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145379

The question is evolving and I'm not going to track it by revising this answer correspondingly.

Yes, for a trivially copyable object you can use memcpy, and that's used in a (non-normative) example in the standard.

C++11 §3.9/2:

For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char. If the content of the array of char or unsigned char is copied back into the object, the object shall subsequently hold its original value.

For template code you can check whether a type is trivially copyable via std::is_trivially_copyable.

Upvotes: 1

Related Questions