Plain Old Data and `std::memcpy` alignment issues

依然范特西╮ 提交于 2019-12-25 07:17:34

问题


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 type T, if two pointers to T point to distinct T objects obj1 and obj2, where neither obj1 nor obj2 is a base-class subobject, if the underlying bytes (1.7) making up obj1 are copied into obj2, obj2 shall subsequently hold the same value as obj1.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!