gpt4 book ai didi

c++ - memcpy 非 POD 对象

转载 作者:太空狗 更新时间:2023-10-29 20:03:45 25 4
gpt4 key购买 nike

对于 POD 类型的对象,标准保证当您将对象的内容 memcpy 到一个数组中时char 或 unsigned char,然后 memcpy 将内容返回到您的对象中,该对象将保留其原始值。

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

Source of the text above

最佳答案

平凡可复制类的原因(C++11 主要使用概念平凡类标准布局类 而不是 POD) can be memcpy'ed 与其他答案/评论所建议的动态分配无关。诚然,如果您确实尝试对具有动态分配的类型进行浅拷贝,那么您就是在自找麻烦。但是您很可能拥有一个带有指针的类型,该指针在用户提供的构造函数中进行动态分配(只要它具有默认构造函数)并符合普通类的条件。

可以保证 memcpy 的实际原因是普通可复制(以及标准布局)类型需要占用连续的存储字节,而其他对象则不需要.

N3690

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.

关于c++ - memcpy 非 POD 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26227965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com