普通旧数据和`std :: memcpy`对齐问题 [英] Plain Old Data and `std::memcpy` alignment issues

查看:141
本文介绍了普通旧数据和`std :: memcpy`对齐问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试回答另一个问题,我提出了一个解决方案使用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 chars.

我对存储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对象obj1obj2,则其中 如果复制组成obj1的基础字节(1.7),则obj1obj2都不是基类子对象. 进入obj2obj2随后应保持与obj1相同的值.

[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.

由于double可轻松复制,因此您的代码定义明确.

Since double is trivially copyable, your code is well-defined.

这篇关于普通旧数据和`std :: memcpy`对齐问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆