普通旧数据和`std :: memcpy`对齐问题 [英] Plain Old Data and `std::memcpy` alignment issues
问题描述
尝试回答另一个问题,我提出了一个解决方案使用std::memcpy()
将通用类型存储在char
s的缓冲区中.
Trying to respond to another question, I've proposed a solution that use std::memcpy()
to store generic types in a buffer of char
s.
我对存储POD的内存对齐问题存有疑问(我知道非POD类型(如std::string
那样非常危险).
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?
如果是的话,是否有可能编写类似的东西(将POD值存储在char
缓冲区中)安全吗?以及如何?
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;
}
推荐答案
这很安全.
[basic.types]/2:
对于任何普通可复制类型T
,如果两个指向T
的指针指向不同的T
对象obj1
和obj2
,则其中 如果复制组成obj1
的基础字节(1.7),则obj1
和obj2
都不是基类子对象. 进入obj2
,obj2
随后应保持与obj1
相同的值.
[basic.types]/2:
For any trivially copyable typeT
, if two pointers toT
point to distinctT
objectsobj1
andobj2
, where neitherobj1
norobj2
is a base-class subobject, if the underlying bytes (1.7) making upobj1
are copied intoobj2
,obj2
shall subsequently hold the same value asobj1
.
由于double
可轻松复制,因此您的代码定义明确.
Since double
is trivially copyable, your code is well-defined.
这篇关于普通旧数据和`std :: memcpy`对齐问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!