加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用std :: memcpy在内存中移动对象

发布时间:2020-12-16 10:24:43 所属栏目:百科 来源:网络整理
导读:是否允许将类实例对象从一个位置移动到另一个位置(例如,通过使用std :: memcpy或std :: memove?假设源位置和目标位置具有相同的对齐方式.然后将目标“object”转换为源对象的类型并调用它.C 11标准的哪一部分禁止这个? 解决方法 只要它们是 is_trivially_c
是否允许将类实例对象从一个位置移动到另一个位置(例如,通过使用std :: memcpy或std :: memove?假设源位置和目标位置具有相同的对齐方式.然后将目标“object”转换为源对象的类型并调用它.C 11标准的哪一部分禁止这个?

解决方法

只要它们是 is_trivially_copyable,它就是安全的.

§3.9.2

For any object (other than a base-class subobject) of trivially copyable type T,whether or not the object holds a valid value of type T,the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char.40 If the content of the array of char or unsigned char is copied back into the object,the object shall subsequently hold its original value.

#define N sizeof(T)
char buf[N];
T obj; // obj initialized to its original value
std::memcpy(buf,&obj,N); // between these two calls to std::memcpy,// obj might be modified
std::memcpy(&obj,buf,N); // at this point,each subobject of obj of scalar type
                           // holds its original value

§3.9.3

对于任何简单的可复制类型T,如果指向T的两个指针指向不同的T对象obj1和obj2,其中obj1和obj2都不是基类子对象,如果构成obj1的基础字节(1.7)被复制到obj2,41 obj2中随后应保持与obj1相同的值. [例如:

T* t1p;
T* t2p;
    // provided that t2p points to an initialized object ...
std::memcpy(t1p,t2p,sizeof(T));
    // at this point,every subobject of trivially copyable type in *t1p contains
    // the same value as the corresponding subobject in *t2p

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读