memcpy一个非POD对象 [英] memcpy a non-POD object

查看:1545
本文介绍了memcpy一个非POD对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于POD类型的对象,通过标准保证当你将对象的内容memcpy为
char或unsigned char的数组,然后将内容回写到你的对象时,对象将保持其原值。

For objects of POD types it is guaranteed by the standard that when you memcpy the contents of your object into an array of char or unsigned char, and then memcpy the contents back into your object, the object will hold its original value.

现在请注意,对于非POD类型的对象没有这样的保证。所以我的问题是为什么是这样的?

Now note that there is no such guarantee for objects of non-POD types. So my question is why is this so?

上述文字的来源

推荐答案

>)可以memcpy'ed是不相关的动态分配作为其他答案/评论建议。授予,如果你尝试一个类型的动态分配的浅拷贝,你是邀请麻烦。但你可以很好地有一个类型的指针,在用户提供的构造函数中动态分配(只要它有一个默认构造函数),并且符合琐碎类

The reason a trivially copyable class (C++11 mostly uses the concepts trivial class and standard-layout class instead of POD) can be memcpy'ed is not related to dynamic allocation as other answers/comments suggest. Granted, if you do try a shallow copy of a type that has dynamic allocation, you are inviting trouble. But you could very well have a type with a pointer that does dynamic allocation in a user provided constructor (as long as it has a default constructor) and qualify as trivial class.

可以保证memcpy的实际原因是,为了占用连续字节的存储空间,需要使用平凡可复制(以及标准布局而其他对象则不是。

The actual reason a memcpy can be guaranteed is that trivially copyable (and also standard-layout) types are required to occupy contiguous bytes of storage whereas other objects are not.

N3690


比特字段(9.6),最导出的对象应具有非零大小,并且将占用一个或多个
字节的存储空间。基类子对象可以具有零大小。普通可复制或标准布局的对象
类型(3.9)将占用连续的存储字节。

1.8.5 Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class subobjects may have zero size. An object of trivially copyable or standard-layout type (3.9) shall occupy contiguous bytes of storage.

这篇关于memcpy一个非POD对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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