问题
Trying to respond to another question, I've proposed a solution that use std::memcpy() to store generic types in a buffer of chars.
My doubt is about possible memory alignment issues storing POD (I know that with not-POD type, as std::string, is very very dangerous).
In short: there are memory alignment issues with the following program?
And if they are, it's possible to write something similar (that store POD values in a char buffer) that is safe? And how?
#include <cstring>
#include <iostream>
int main()
{
char buffer[100];
double d1 { 1.2 };
std::memmove( buffer + 1, & d1, sizeof(double) );
double d2;
std::memmove( & d2, buffer + 1, sizeof(double) );
std::cout << d2 << std::endl;
return 0;
}
回答1:
This is safe.
[basic.types]/2:For any trivially copyable typeT, if two pointers toTpoint to distinctTobjectsobj1andobj2, where neitherobj1norobj2is a base-class subobject, if the underlying bytes (1.7) making upobj1are copied intoobj2,obj2shall subsequently hold the same value asobj1.
Since double is trivially copyable, your code is well-defined.
回答2:
You can copy to and from an unaligned buffer. What you can't do is cast the buffer to a double * and then operate directly on the value in memory, as a double. Often that will cause an error because of alignment issues.
来源:https://stackoverflow.com/questions/39832733/plain-old-data-and-stdmemcpy-alignment-issues